Lesson · Exceptions & Defensive Programming
Exception Chaining
55 min readException Chaining
Exception chaining preserves both the high-level error and the low-level cause. `raise ... from ...` is especially useful at abstraction boundaries such as parsers, repositories, and service clients.
Learning goals
- Write a translation that attaches the original failure with
from exc, and say where that original now lives on the new exception. - Tell
__cause__and__context__apart: what sets each, and what a traceback shows for each. - Choose between bare
raise,raise ... from exc, andraise ... from Nonefor a given situation. - Read a chained traceback and name both the domain error and the low-level cause it preserves.
Mental model
Both attributes point back to the original failure: __cause__ when you used from, and __context__ when a new exception is raised while another is in flight. The traceback prints one section per link, so a reader sees the domain error first and the low-level cause underneath. Chaining is how a boundary reports that it could not load the record without hiding the decoder error that explains why.
Mental model
read it top to bottom
except ValueError as exc:
raise DataError(...) from exc → exc becomes __cause__ (direct cause)
raise DataError(...) → exc becomes __context__ (during handling)
raise DataError(...) from None → context hiddenCore idea
An exception that crosses a boundary should answer two questions: what failed at this level, and what went wrong underneath. raise ... from keeps the original attached as __cause__, while any exception raised during handling attaches the original as __context__ automatically. The choice of from exc or from None is a statement about how much of the lower layer the caller should see.
raise ... from ...
raise ... from ... explicitly records one exception as the cause of another. It is the clearest way to translate low-level implementation failures into domain-level errors.
Explicit cause
Explicit chaining with from records the original exception as __cause__. Debuggers and tracebacks then show both the domain error and the underlying failure.
Implicit context
When one exception arises while another is already being handled, Python records the earlier exception as context. Explicit chaining can clarify whether that relationship is intentional.
Preserving traceback information
Preserving traceback information means keeping the original exception attached to the new one so its type, message, and frames stay readable after translation: raise DataError(...) from exc stores it as __cause__, and the traceback renders both levels in order. Flattening the cause into a string keeps a hint of it but loses the type and the frames, which is often exactly what you need when the domain message is not enough.
Walkthrough
int(text)raisesValueErrorfor"abc", and the handler binds it to the nameexcwithexcept ValueError as exc, which keeps the original object available while the new error is built.raise DataError(f"invalid number: {text!r}") from exccreates the domain error and recordsexcas its__cause__. The!rconversion surrounds the bad text with quotes in the message.- The caller's
except DataError as exccatches the domain error and walks one level down:type(exc.__cause__).__name__printsValueError, which shows the lower failure was preserved as an object rather than flattened into text. - Predict before running: what the two
printcalls show, and what changes about both whenfrom excis deleted.
Experiments to try
- Run both paths:
load_number("42")returns42, whileload_number("abc")raisesDataError. Compare the returned value with the traceback of the failing call. - Delete
from excand re-run the failing call. Note that__cause__becomesNoneand the traceback now labels the original as occurring during handling. - Replace
from excwithfrom Noneand re-run. Note which exception disappears from the displayed traceback. - Chain one more level: catch
DataErrorin a helper and raise a newConfigErrorfrom it, then read the traceback and count the links.
Common mistakes
- Converting a low-level failure into a domain error without
from: the original still attaches as__context__, but the traceback labels the link as accidental handling rather than a designed translation. - Expecting
__cause__when there was nofrom: code that inspectsexc.__cause__seesNoneeven though the previous exception is reachable asexc.__context__. The two links are not interchangeable. - Passing a failure upward with
raise exc: it re-raises the same object but appends the current frame to the traceback, so every layer adds a frame that contributes nothing. Bareraisepreserves the original traceback. - Wrapping at every layer: chaining the same failure through three functions repeats the same frame information. Chain where the error's meaning changes, normally at the boundary.
Practice: Easy
- Run
load_number("42")andload_number("abc"). For the failing call, printexc.args[0],type(exc.__cause__).__name__, andexc.__context__. - Delete
from excand re-run the failing call. Record how the traceback labels change and what__cause__holds now. - Replace
from excwithfrom Noneand re-run. Record which exception the traceback shows and which it drops.
Practice: Medium
- Add a
read_number_line(path)function that opens a file and passes its text toload_number, translating anyOSErrorinto aDataErrorwithfrom exc. Test a real path, a missing path, and a non-numeric line, and read the chain in each traceback. - Write two versions of one conversion, one with
from excand one that copiesstr(exc)into the message only. Compare what each logs when the top-level handler catchesDataError. - Take a conversion in your own code that raises a new exception inside an
exceptblock, and decide for each case whether it is a translation (from exc), an expected condition (from None), or a pass-through (bareraise).
Practice: Hard
- Design a two-layer loader (raw text, then a domain record) where each boundary translates one failure into that layer's vocabulary. Define for each boundary the exception raised, its
fromtarget, and what a caller one level up sees. - Build a failure lab that produces three tracebacks for the same root failure: no
from,from exc, andfrom None. Annotate the header line each produces and decide which is correct for theload_numbercase. - Connect this lesson to custom exceptions (lesson 72) and exception groups (lesson 74): describe where a chain stays single-cause and where an
ExceptionGroupis the right shape instead, using one scenario from your own code.
Lesson checklist
- I can write a translation that attaches the original failure with
from excand point to where the original went (__cause__). - I can explain the difference between
__cause__and__context__and what sets each one. - I can choose between bare
raise,raise ... from exc, andraise ... from Nonefor a given situation. - I can read a chained traceback and name both the low-level cause and the domain error it produced.
Remember
Exception chaining keeps the original failure attached when a boundary translates it: `from exc` records it as `__cause__`, and a raise that happens while another exception is in flight records it as `__context__` automatically. The traceback prints both, so a caller sees the domain-level error and the underlying cause. Use `from exc` for deliberate translations, `from None` when the lower layer is noise, and bare `raise` to pass a failure upward unchanged.
Interview angles
What is the main purpose of **raise ... from ...**?+
raise ... from ... explicitly records one exception as the cause of another. It is the clearest way to translate low-level implementation failures into domain-level errors.
What should you pay attention to when using **Explicit cause**?+
Explicit chaining with from records the original exception as __cause__. Debuggers and tracebacks then show both the domain error and the underlying failure.
How does **Implicit context** fit into this lesson?+
When one exception arises while another is already being handled, Python records the earlier exception as context. Explicit chaining can clarify whether that relationship is intentional.
What does `exc.__cause__` contain when a handler raises a new exception without `from`, and where does the original exception live instead?+
__cause__ is None; the earlier exception is attached automatically as exc.__context__, and the traceback labels it as occurring during handling of the previous exception. Using from exc sets __cause__ and makes the translation explicit.