Lesson · Exceptions & Defensive Programming
Exception Fundamentals
70 min readException Fundamentals
Exceptions separate error signaling from normal return values. Robust code raises errors at the point of detection and catches them only where it can add context, recover, or translate the failure.
Learning goals
- Explain the
BaseExceptiontoExceptionhierarchy and why catchingExceptionalso catches every subclass beneath it. - Raise the most meaningful built-in exception type at the point where an operation cannot satisfy its contract.
- Structure a
trystatement withexcept,else, andfinally, and state which blocks run for a success, a handled failure, and an unhandled failure. - Predict the control flow of
parse_agefor a valid string, an unparsable string, and a negative number.
Mental model
An exception propagates by walking the call stack: Python looks for a matching except in the frame that raised, then in each caller in turn. A match resumes normal execution after the try statement; if no frame matches, the interpreter prints the traceback and the program stops. else and finally sit on the same path: else runs only when the try block finished without an exception, and finally runs on every way out.
The search walks outward from the raise site
innermost frame first, one frame at a time
Mental model
the same mechanism as a compact list
raise exception → search current frame → unwind → parent frame → handler
Core idea
Every failure has three jobs: detect it, signal it, and handle it, and a try statement is where those jobs are assigned. raise signals that an operation cannot satisfy its contract, except decides whether this frame is the one that can recover or add context, and else/finally keep the success path and the cleanup out of the handler. The design rule is to signal where the problem is detected and handle only where something useful can be done about it.
Exception hierarchy
Python exception classes form an inheritance hierarchy rooted under BaseException, with most application errors under Exception. Catching a base type also catches its subclasses.
Raising exceptions
Use raise when the current operation cannot satisfy its contract. Raise the most meaningful exception type and include context that helps identify the invalid state or input.
Catching exceptions
Catch an exception only where the code can recover, retry, translate, clean up, or add context. Narrow handlers reduce the chance of hiding unrelated bugs.
try
A try block marks operations whose exceptions you intend to handle nearby. Keep it as narrow as practical so unrelated programming errors are not accidentally caught.
except
An except clause catches matching exception types. Catch specific types and only at a level that can recover, translate, retry, or add useful context.
else
The else clause of a try statement runs only when the try block finishes without raising an exception. It sits between the except clauses and finally, which keeps the protected region small: code that should run only on success lives in else, so the handlers do not accidentally catch exceptions that come from it.
finally
A finally block runs as control leaves the try statement, whether by normal completion, exception, return, or many other transfers. It is meant for cleanup that must occur.
Walkthrough
int(text)is the operation allowed to fail, so it is the only statement insidetry. A non-numeric string raisesValueError, and the matchingexcept ValueErrorconverts the failure intoreturn None.elseruns only whenint(text)succeeded, which is whereage < 0raises a freshValueErrorwith the messageage must be non-negative. The siblingexceptdoes not catch it, becauseelseexecutes outside the protected region.finallyprintsparse attempt completeexactly once on every path: valid input, unparsable input, and negative age all reach it before the function returns or the exception travels upward.- Predict before running: what
parse_age("42")prints and returns, and how the output and result change forparse_age("abc")andparse_age("-5").
Experiments to try
- Run
parse_age("abc")andparse_age("-5")in the REPL. For each call, list which blocks ran and what value or exception left the function. - Move the
age < 0check inside thetryblock and callparse_age("-5")again. Explain why the caller now receivesNoneinstead of aValueError. - Replace
except ValueErrorwith a bareexcept:and callparse_age(None)to see theTypeErrorfromint(None)get swallowed. Restore the specific handler afterward. - Add a
printat the top of each block (try,except,else,finally) and run all three inputs to confirm the order in which the blocks execute.
Playable lesson
Lab: Exception stack unwinding
Display nested frames, raise an exception in the deepest frame, and animate handler search plus frame unwinding.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Exception unwinding
Call stack (newest on top)
- parse_port()no try statementwaiting
- load_config()no try statementwaiting
- main()except ValueErrorwaiting
Frames left
3
still to be searched
Program
running
Predict first
`parse_port` raises. Which frame does Python examine for a handler first?
Three frames are alive: `main` called `load_config`, which called `parse_port`. Nothing has failed yet, so every frame is parked on the call below it.
The search only ever moves outward, from the raise site toward the caller.
Common mistakes
- Wrapping a whole function in
except Exception(or a bareexcept:): a broad type matches unrelated defects such asTypeErrororNameError, so real bugs are silently converted into normal returns. - Swallowing an exception with
passand no record: the caller cannot distinguish "invalid input" from "valid result", and nothing remains for debugging. - Keeping too much code inside
try: every statement after the risky call is covered by the same handler, so an unrelated failure in the success path can be misreported as the expected error. Move success-only logic toelse. - Doing real work in
finallythat can raise: the new exception displaces the one already propagating, so the traceback leads with the cleanup failure and the original cause survives only as chained context.
Practice: Easy
- Run the worked example, then call
parse_age("42"),parse_age("abc"), andparse_age("-5")in the REPL. For each call, note the value or exception that leaves the function and which blocks ran. - Try
parse_age(" 42 ")andparse_age("4.2"). Explain both results fromint's behavior: it tolerates surrounding whitespace but rejects strings that are not whole numbers, raisingValueError. - Trigger the unhandled
ValueErrorwithparse_age("-5")and read the traceback from the bottom up. Name the line that raised, the line that called, and the exception message.
Practice: Medium
- Rewrite
parse_ageso the negative-age check raises inside thetryblock, and describe what the caller now receives for"-5". Decide which version you would ship and why. - Add a
parse_quantity(text)function that follows the same structure but includes the offending text in itsValueErrormessage. Show the exact message that reaches the caller. - Find a function of yours that returns
Nonefor several distinct failures, and give each failure its own exception type. List what a caller can now tell apart.
Practice: Hard
- Design a small parsing module with
parse_age,parse_price, and amain()that reads lines fromsys.stdinand reports per-line failures without stopping. State which exception types cross which function boundaries before writing code. - Build a failure lab that demonstrates four mechanics from this lesson's mistakes: a broad
exceptswallowing aTypeError, afinallythat raises over a live exception, areturninsidefinallythat discards it, and a handler catchingBaseExceptionthat also swallowsKeyboardInterrupt. - Draft a library boundary where an internal
ValueErrorfrom parsing is translated into a documented public exception, and note whereraise ... from(lesson 73) would preserve the original cause.
Lesson checklist
- I can describe how an exception unwinds frames until a matching
exceptruns, and what happens when no frame matches. - I can assign the four blocks of
parse_age(try,except,else,finally) to the job each one does. - I can raise the correct built-in type with a useful message instead of returning a sentinel
None. - I can explain why a bare
except:hides bugs instead of handling them.
Remember
An exception is control flow with a search: `raise` signals that an operation cannot meet its contract, and the interpreter unwinds frames until an `except` matches or the program stops. A `try` statement splits that flow into four jobs: the protected operation, the handler, the success continuation in `else`, and the unconditional exit in `finally`.
Interview angles
What is the main purpose of **Exception hierarchy**?+
Python exception classes form an inheritance hierarchy rooted under BaseException, with most application errors under Exception. Catching a base type also catches its subclasses.
What should you pay attention to when using **Raising exceptions**?+
Use raise when the current operation cannot satisfy its contract. Raise the most meaningful exception type and include context that helps identify the invalid state or input.
How does **Catching exceptions** fit into this lesson?+
Catch an exception only where the code can recover, retry, translate, clean up, or add context. Narrow handlers reduce the chance of hiding unrelated bugs.
Why is `except Exception` (or a bare `except:`) around a whole function a problem even when the program no longer crashes?+
It matches every exception under it, including unrelated defects such as TypeError or NameError, so genuine bugs are silently converted into normal returns. Catch the specific type the operation can raise, and keep the try block limited to the operation that fails.