Python Exception Handling (`try/except/else/finally`) Tracing
Robust Python programs anticipate and handle runtime errors cleanly using `try / except / else / finally` blocks. Tracing how `finally` guarantees execution (even overriding `return` statements!) and how exception class hierarchies match in `except` blocks (`ordering Specific before General`) is critical.
Core Conceptual Insights
Theoretical Blueprint:A `finally` block is like an airplane's emergency landing brake: no matter what autopilot command (`return`) or engine alarm (`exception`) happened during the flight, the brake always deploys at touchdown.
Common Developer Trap:Many developers don't know that if both `try` and `finally` contain `return` statements, the `finally:` return statement completely replaces and overrides the `try:` return value!
Structured Practice Breakdown
`finally` block overriding `return` value
def test():
try:
return 'from try'
finally:
return 'from finally'
print(test())from finallyExecution Walkthrough
When `return 'from try'` runs, execution pauses to run `finally:`. Because `finally` returns `'from finally'`, that value overrides the `try` return. Output: `from finally`.
`try / except / else / finally` execution sequence
try:
x = 10 / 2
except ZeroDivisionError:
print('Error')
else:
print('Success')
finally:
print('Cleanup')Success
CleanupExecution Walkthrough
No exception raised -> `else:` runs (`'Success'`) -> `finally:` runs (`'Cleanup'`). Output: `Success` followed by `Cleanup`.
Exception hierarchy order trapping
try:
d = {}
print(d['missing'])
except Exception:
print('General Exception caught')
except KeyError:
print('KeyError caught')General Exception caughtExecution Walkthrough
`KeyError` is a subclass of `Exception`. Because `except Exception:` sits at the top, it intercepts `KeyError` and prints `'General Exception caught'`.
Catching multiple exceptions in one tuple
try:
int('abc')
except (ValueError, TypeError) as e:
print(type(e).__name__)ValueErrorExecution Walkthrough
`int('abc')` raises `ValueError`. It matches the tuple `(ValueError, TypeError)` and prints the exception type name: `ValueError`.