Lesson · Exceptions & Defensive Programming
Exception Design & Exception Groups
79 min readException Design & Exception Groups
Exception design is about boundaries, not just syntax. `ExceptionGroup` and `except*` extend the model to multiple simultaneous failures, which is especially relevant to structured concurrency.
Learning goals
- Catch the narrowest type around the smallest region, and explain why a broad handler converts bugs into normal-looking results.
- Decide at a boundary whether to translate a low-level failure into a domain type or let it propagate unchanged.
- Sort a failure into cleanup, recovery, or retry, and pick the response that matches.
- Read
ExceptionGroupoutput: which failures matched anexcept*clause and which stayed raised. - Write exception messages that name the operation, the input, and the reason the call cannot continue.
Mental model
The four questions are the design order: first choose the layer and the types, then decide whether the response is cleanup, recovery, or a bounded retry, and only then write the message and the handler. ExceptionGroup adds one branch to the model: when several failures arrive together, except* splits them by type instead of catching the whole bundle.
One group in, one group out
except* partitions by type; the leftovers travel on
Mental model
the same mechanism as a compact list
Where can this failure be handled? → catch narrowly Where does its meaning change? → translate into a domain error Which layer owns the contract? → the exception boundary One failure or many at once? → ExceptionGroup with except*
Core idea
Exception design assigns each failure to the layer that knows what to do with it: handlers catch narrowly, boundaries translate into the local vocabulary, and failures nobody can act on propagate. The same design decides the response shape: cleanup before propagating, recovery with a fallback, or a bounded retry for transient errors. ExceptionGroup and except* extend these rules to operations that fail several ways at once.
Catch narrowly
Catching narrowly means each handler names the specific exception types it can actually recover from, and the try block covers only the operations that can raise them. A broad except Exception around a large block also matches programming errors from later statements, so the handler silently converts a bug into a normal-looking result. Narrowing both the types and the region is what keeps a handler honest about what it handles.
Translate low-level errors into domain errors
Translation means the boundary re-raises a failure in the vocabulary of its own layer: a repository converts a decoder's ValueError into RecordCorruptError, keeping the original attached with from exc. Callers above the boundary then catch meaningful domain types instead of importing knowledge of the lower library's internals. Translate once, at the boundary, rather than at every internal call.
Exception boundaries
An exception boundary is a place where the failure vocabulary changes, normally a module, package, or service edge: below it live implementation-specific errors; above it are the types the public contract promises. The boundary layer catches what it understands, translates it, and lets everything else propagate unchanged. The design question at each boundary is which failures the caller is expected to handle and which are left to crash.
Cleanup vs recovery
Cleanup and recovery are different responses to a failure: cleanup releases what the interrupted operation held (files, locks, transactions) and then lets the failure continue, while recovery decides the failure is handled and produces a normal result instead. finally and context managers do cleanup; an except that returns a fallback or retries does recovery. Conflating them is how a handler ends up swallowing an error just because it had something to close.
Retryable vs non-retryable failures
A retryable failure is transient: the same call can succeed later, for example a timeout or a temporarily locked resource, so a bounded retry loop is reasonable. A non-retryable failure reflects the call itself, such as invalid input or a missing attribute, and retrying it just repeats the same failure. Giving the two kinds distinct exception types, or a documented attribute, lets the retry logic exist in one place instead of guessing from messages.
Error-message design
A good exception message says what operation failed, on what input, and why it cannot continue, in that order: invalid number: 'abc' beats error. Messages are read in tracebacks and logs where the surrounding code is not visible, so include the values involved. The type carries the category; the message carries the specifics the type cannot.
When not to catch an exception
Some failures should not be caught at all: programming errors such as AttributeError or wrong argument types usually mean the code must change, not that the program should continue with a fallback. KeyboardInterrupt and SystemExit derive from BaseException and exist to stop the program, so catching them, directly or through a broad except, breaks the user's way out. Catch only failures the code can respond to meaningfully.
ExceptionGroup
ExceptionGroup stores multiple exceptions that arose as part of one logical operation. except* handlers can process matching subgroups while preserving the unmatched failures.
except*
except* is the handler that unpacks an ExceptionGroup: each except* clause extracts the sub-exceptions matching its type into a subgroup and leaves the rest for later clauses or for propagation. Unlike except, a clause runs even when only some contained failures match, and anything unmatched stays raised after the matched part is handled. When the raised exception is not a group, it is treated as a group of one.
Handling failures from concurrent work
Concurrent tasks can fail at the same time, and structured concurrency reports that as one ExceptionGroup rather than delivering failures one at a time or cancelling silently. The group preserves every failure, for example all tasks that failed in a batch, so handling code can process matching errors with except* and re-raise the rest. This is why the group model matters: one logical operation, many failures, none dropped.
Walkthrough
validate_allcollects oneValueErrorper bad value instead of stopping at the first:errors.append(ValueError(f"index {index}: {value}"))builds a list of plain exceptions, each carrying its position and value in the message.raise ExceptionGroup("invalid values", errors)packages the list into one group with a message for the whole operation. The group message describes the batch; each contained exception describes its own failure.except* ValueError as groupdoes not catch one exception but extracts everyValueErrorin the group into a subgroup, and the loop overgroup.exceptionsprints each member. If the group also contained aTypeError, the unmatched part would stay raised after this clause.- Predict before running: how many lines the handler prints for
validate_all([2, -1, 5, -3]), and whatvalidate_all([1, 2])does.
Experiments to try
- Run the worked example, then call
validate_all([1, 2])and confirm that nothing is raised whenerrorsstays empty. - Call
validate_all([2, "x", -3])and observe where the comparisonvalue < 0fails and with which type; decide whether that is a caller bug or somethingvalidate_allshould translate. - Add a
TypeError("count mismatch")member to the group, re-run, and note that theexcept* ValueErrorblock prints only theValueErrormembers while theTypeErrorstill propagates. - Replace the
except*clause with plainexcept ValueError:and run. The handler never runs, because the raised object is anExceptionGroup, not aValueError, and the whole group propagates.
Playable lesson
Lab: ExceptionGroup splitter
Create several failures and show how except* partitions matching and non-matching sub-exceptions.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
ExceptionGroup splitter
Sub-exceptions in the group
- TimeoutErrorfetch("config")pending
- TimeoutErrorfetch("catalog")pending
- ValueErrorparse("rows")pending
- KeyErrorlookup("theme")pending
Handlers
except* TimeoutError
not reached yet
waits for the group
except* ValueError
not reached yet
waits for the group
Handled
0
of 4 sub-exceptions
Re-raised
0
left for the caller
Predict first
How many exception objects does the join point raise?
Four units of work run together and each one fails differently. Instead of stopping at the first failure, the framework collects all four into a single `ExceptionGroup` and raises that one object at the join point.
Common mistakes
- Using plain
exceptfor grouped failures: anExceptionGroupis not an instance of its members' types, soexcept ValueErrornever runs for a group containing aValueError. Onlyexcept*splits the group, unless the handler catchesExceptionGroupitself. - Catching to clean up and forgetting to re-raise: a handler that frees a resource and then returns normally converts the failure into success; cleanup belongs in
finallyor a context manager, or must end with a bareraise. - Retrying everything: a retry loop wrapped around a non-retryable failure such as invalid input repeats the same error until the attempt budget runs out and hides the real cause.
- Writing messages that restate the type:
raise ValueError("invalid value")adds nothing a handler or a reader can use; the message should carry the operation, the offending value, and the reason.
Practice: Easy
- Run the worked example and record how many exceptions are printed, their messages, and the type of the object
validate_allraises. - Call
validate_all([1, 2])andvalidate_all([-1]). Describe the difference between an empty list of failures and a one-member group. - Print
group.exceptionsand the class of each element inside the handler, and confirm that every member is anExceptioninstance rather than a nested group.
Practice: Medium
- Extend
validate_allso one call can report two failure kinds: negative values asValueErrorand non-integer values asTypeError. Add a secondexcept*clause and confirm which members each clause handles. - Add a
TypeErrormember to the group on purpose and leave the handler asexcept* ValueError. Record what happens to the unmatched failure and where it surfaces. - Rewrite one broad
except Exceptionin your own code as a narrow handler plus a boundary translation withfrom exc, and list the failure categories the broad version was hiding.
Practice: Hard
- Design a validation module whose public function raises an
ExceptionGroupwith at most one error per input row. Document the member types, the group message, and what a caller should do with each member before writing code. - Build a boundary lab: a low-level function raising three different built-in types, a boundary that translates one of them, and a top level that catches the domain type while letting the other two crash. Annotate which layer owns each failure and why.
- Connect this lesson to structured concurrency (a later module): describe how failures from several tasks arrive in one
ExceptionGroup, and sketch theexcept*clause that handles one failure kind while allowing the rest to propagate.
Lesson checklist
- I can point to the boundary in a call chain and say which exception types cross it and which do not.
- I can rewrite a broad handler as a narrow one plus an explicit translation.
- I can classify a failure as cleanup, recovery, or retry before writing the handler.
- I can explain how
except*splits anExceptionGroupand what happens to unmatched members.
Remember
Exception design decides three things: which layer catches, what the failure is called there, and whether the response is cleanup, recovery, or a bounded retry. Catch narrowly, translate once at the boundary with `from exc`, and let everything you cannot handle propagate. When one operation fails several ways at once, `ExceptionGroup` carries all members and `except*` handles the matching ones while the rest stay raised.
Interview angles
What is the main purpose of **Catch narrowly**?+
Each handler names the specific exception types it can actually recover from, and the try block covers only the operations that can raise them. Narrowing both the types and the region is what keeps a handler honest about what it handles.
What should you pay attention to when using **Translate low-level errors into domain errors**?+
Translation re-raises a failure in the vocabulary of the boundary's own layer, keeping the original attached with from exc. Callers above the boundary then catch meaningful domain types instead of importing knowledge of the lower library's internals.
How does **Exception boundaries** fit into this lesson?+
A boundary is where the failure vocabulary changes: below it live implementation-specific errors; above it are the types the public contract promises. The boundary layer catches what it understands, translates it, and lets everything else propagate unchanged.
Why does `except ValueError` fail to catch a `ValueError` inside an `ExceptionGroup`, and what handles it instead?+
An ExceptionGroup is a container, not a subclass of its members' types, so a plain handler for ValueError never matches the group object itself. Only except* extracts and handles the matching members, leaving the rest raised.