Exceptions in Depth
Turn crashes into controlled, recoverable events
Big idea: An exception is Python's way of signalling that something went wrong as a value that travels up the call stack. Instead of returning error codes and checking them by hand, you let the failure interrupt normal flow, then catch it exactly where you can do something useful about it. You already met
try/except in the beginner course; here you will control the full lifecycle: try, except, else, finally, deliberately raise-ing errors, designing your own exception types, and chaining one failure to another.
By the end you will be able to:
- use all four blocks —
try,except,else,finally— and say what each is for, - catch specific exception types (and why bare
except:is a trap), raiseexceptions on purpose, including re-raising,- design custom exceptions by subclassing
Exception, - preserve the original cause with exception chaining (
raise ... from ...).
1. The full anatomy: try / except / else / finally
A complete exception handler has up to four parts. Only try plus at least one except (or a finally) is required; else and finally are optional but powerful.
try:
# 1. the risky work
value = int(user_input)
except ValueError:
# 2. runs ONLY if a matching exception was raised in try
print("That was not a whole number.")
else:
# 3. runs ONLY if try finished with NO exception
print("You entered", value)
finally:
# 4. ALWAYS runs — success, failure, or even return
print("Done validating.")
The key distinction most people miss is between else and putting more code at the bottom of try:
tryshould hold only the line(s) that can fail. Keep it small so you know exactly what anexceptis catching.excepthandles one kind of failure. You may have several, checked top to bottom; the first matching one wins.elseholds the "everything worked" follow-up. Because it runs only whentrysucceeded, an exception raised here is NOT caught by theexceptabove it — that is exactly the point.finallyis for cleanup that must happen no matter what: closing files, releasing locks, restoring state. It runs even if youreturnfrom insidetry.