Search code examples
pythonexceptionerror-handlingcode-readability

Correct extent of the exception handling block


Lets say we have the following code:

print("...")
might_throw_type_error()
print("...")
might_throw_index_error()

If we want to handle the exceptions that those functions might arise what is the preferred way:


Full split of "business" code and error handling

try:
    print("...")
    might_throw_type_error()
    print("...")
    might_throw_index_error()
except IndexError:
    # index error handling logic
    raise
except TypeError:
    # index error handling logic
    raise

Split of logic and error handling but try starting at the first statement that might raise

print("...")
try:
    might_throw_type_error()
    print("...")
    might_throw_index_error()
except IndexError:
    # index error handling logic
    raise
except TypeError:
    # index error handling logic
    raise

Exception handling should only wrap statements we expect to raise

print("...")
try:
    might_throw_type_error()
except TypeError:
    # index error handling logic
    raise
print("...")
try:
    might_throw_index_error()
except IndexError:
    # index error handling logic
    raise

Note that if we capture the exception we don't want to continue


Solution

  • It definitely depends on what exactly you want to achieve - consider that if you will use the #1 approach if something will go wrong with the first might_throw_index_error the following print and second might_throw_index_error will never been executed.

    On the second hand the last one guarantees you that at least the secon print will always fire.

    Every of these ways are good but it depends on what you want to do with your application flow.