Python exceptions form a class hierarchy that allows a handler to catch a specific failure or a broader family of failures.
Design domain errors, preserve causes with raise from and distinguish cleanup from recovery.
A renamed column should not turn a failed import into a successful report containing zero rows. Decide which failures the loader can recover from, which need more context, and which are programming bugs. Exception classes and cause chains let those decisions remain visible as failure moves through the program.

Sort a KeyError from a renamed column
Quarry ran all night and reported success: zero errors, zero rows. Somebody had wrapped the loader like this:
try:
load_everything()
except Exception:
passA renamed column made every row raise KeyError. The except caught every
one, said nothing, and the run "succeeded" — a crash would have been better.
KeyError is a class, like every exception; __mro__ lists its ancestors,
nearest first:
Near the top, everything splits in two: BaseException is the root, and
directly under it sit exceptions that are not program errors —
KeyboardInterrupt, SystemExit. Exception contains most ordinary application errors. Cancellation and
process-exit exceptions may sit outside it. A bare except: catches
BaseException too, so a program with one in its main loop can't even be
interrupted with Ctrl+C.
A clause catching a whole subtree has a consequence people trip over — order matters, because the first match wins:
row = {"id": "a1"}
try:
print(row["ms"])
except LookupError:
print("lookup")
except KeyError:
print("key")The right width is about what you'll do next, not which errors might happen:
catch narrowly where you can act (except ValueError: around int(text)),
and never catch just to silence — an exception you let go becomes a
traceback with a line number; one you swallow becomes a mystery. Whether one bad row should abort the batch is a data contract, not a
universal rule: a financial import may require an atomic batch, while a
log inspector may explicitly report partial results.
Preparing this topic’s interactive investigation…
Give Quarry its own error branch
The builtin tree describes how something failed. It can't say what Quarry should do about it — so Quarry defines its own branch, under one base class, named for the response, not the symptom:
Three decisions are packed into those lines. One base class, so
except QuarryError: catches anything Quarry raised on purpose while
letting a genuine bug crash loudly. Names for the response:
SourceError means stop and retry later, BadRowError means skip this row
— the catching code doesn't need to know what went wrong inside. And
BadRowError is also a ValueError, via multiple inheritance, so code
written before Quarry had its own errors still catches it.
An exception class is an ordinary class, so give it the facts the handler will need instead of making it parse a message:
Chain a bad ms value into Quarry's vocabulary
The low-level ValueError from int is the true story, but it's the wrong
vocabulary for a caller who just wants to know "skip or stop?". The loader
catches it and raises its own error, saying where it came from:
raise NEW from OLD stores OLD on NEW.__cause__, and the traceback says
"the above exception was the direct cause". Raise inside an except without
from and Python remembers the handled exception anyway, as __context__,
worded "during handling of the above exception"; that records context,
not a diagnosis of why the second exception occurred. from None suppresses
a noisy original when only the new error's message matters:
try:
try:
{"yard": 1}["vult"]
except KeyError:
raise ValueError("unknown stage 'vult'") from None
except ValueError as err:
print(err.__cause__, err.__suppress_context__)Cleanup belongs in finally, which runs on every way out — success, a
handled error, an unhandled one, even a return:
That guarantee is why this batch loader is wrong — "close" only runs when
the loop finishes clean:
The batch is always supposed to be closed, even when a bad row makes it re-raise. Right now "close" is skipped on the failure path. Make the cleanup unconditional.
Choose the recovery boundary before the exception class
The same low-level exception can require different actions. A ValueError converting one known numeric cell may mean “reject this row”. A ValueError from a parser configuration may mean “the whole run is misconfigured”. Catching by class is only useful when the surrounding operation gives the class a precise meaning.
Trace a conversion failure through three layers:
| Layer | Knows | Appropriate action |
|---|---|---|
| numeric conversion | the raw cell is invalid | raise ValueError |
| row adapter | file and row number | raise BadRowError from that cause |
| batch policy | whether partial results are allowed | record rejection or abort |
Keep the try around the operation whose failure you intend to translate. If it also wraps logging, unrelated lookups and storage, a bug in those operations may be mislabeled “bad input”. Preserve structured facts on the domain exception so the handler need not scrape an error-message string.
raise NewError(...) from old records an explicit cause. Implicit context records that another exception was active, but does not itself prove the handler contains a bug. from None hides context in the usual traceback display; it does not delete the original exception object or make sensitive data safe to retain.
Apply a new policy: a nonexistent source file should stop that source, a malformed row may be skipped, and a KeyError caused by misspelling your own dictionary key should escape. Write down which narrow try owns each one. Then inject the misspelling and verify that it cannot turn into a successful report with zero rows.
References: exception chaining and inheritance and handling exceptions.
Traps worth knowing
A bare raise inside an except re-raises the exception being handled,
traceback intact — how you log-and-rethrow. A return inside finally
replaces whatever was happening, including an in-flight exception, which
vanishes without a trace — never do it. And an exception raised inside
finally replaces the one already in flight, chained with "during handling"
— keep finally bodies small and boring.
Quick practice
class QuarryError(Exception): pass
class BadRowError(QuarryError, ValueError): pass
def kind(exc):
if isinstance(exc, ValueError):
return "bad value"
if isinstance(exc, QuarryError):
return "quarry"
return "bug"
print(kind(BadRowError("x")))try:
try:
raise KeyError("stage")
except KeyError as exc:
raise ValueError("bad stage") from exc
except ValueError as err:
print(type(err.__cause__).__name__, err.__suppress_context__)close_file() is meant to run no matter what — right now a bad value skips it. Wrap the risky line so closing still happens.
🎯 Your turn
Build classify_error(stage, raw). The starter gives you Quarry's error
classes and its real loader, load_row(stage, raw), which can fail three
ways: a SourceError for an empty line, a BadRowError chained from a
ValueError for a malformed row, and a plain KeyError — a bug — when a
field is missing.
Call load_row. Return {"category": ..., "chain": [...]} where the
category is "ok", "bad-row", "source" or "bug", and the chain lists
the class names from the error you caught down to its root cause, following
__cause__ first, then __context__ unless it is suppressed.
classify_error("yard", "id=a1;ms=120") # → {"category": "ok", "chain": []}
classify_error("yard", "id=a2;ms=fast") # → {"category": "bad-row", "chain": ["BadRowError", "ValueError"]}
classify_error("vault", "") # → {"category": "source", "chain": ["SourceError"]}Press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write catches(handler, raised). Both arguments are names of builtin exception classes. Return True if except <handler>: would catch an exception of class <raised>, else False.
Write ancestry(name): for the builtin exception class called name, return the names of the class and all its ancestors, nearest first, stopping at BaseException (leave out object).
A try has several except clauses, given in order as handlers. Each is a builtin class name, or a list of names for a tuple clause like except (TypeError, ValueError):. Write first_handler(handlers, raised) returning the index of the clause that catches an exception of class raised, or -1 if none does and it propagates.
The starter defines five failure scenarios. Write traceback_outline(case): run SCENARIOS[case](); if it raises, return the outline Python would print, root cause first: class names, with "direct cause" between two errors linked by __cause__ and "during handling" between two linked by an unsuppressed __context__. If nothing is raised, return [].
Using Quarry's loader from the starter, write safe_rows(stage, lines). Load each line in order with load_row. A BadRowError means skip that line (record its index); a SourceError means stop the batch at once (record the index); any other exception is a bug and must propagate. Return {"loaded": [ids of loaded rows], "skipped": [indices], "stopped_at": index or None}.
Quarry's old loader wrapped the whole run in try: ... except Exception: pass and reported success with zero rows after a column was renamed. Explain what was wrong with that handler and what you would write instead.