Python Exception Groups and except*
Learn how Python groups independent exceptions and handles matching subgroups with except*.
Intermediate
Sometimes a program has several independent failures to report together. Python's
ExceptionGroup lets one exception value carry multiple exceptions, while
except* can handle the matching parts without treating the whole group as one ordinary exception.
Create and raise an exception group
An
ExceptionGroup has a message and a sequence of nested exceptions. You can raise it like any other exception. When all nested exceptions inherit from
Exception the constructed group is an
ExceptionGroup rather than a more general
BaseExceptionGroup.
Output
Ready to run.
Handle matching parts with except*
With
except* Python matches inside the exception group. A handler receives a subgroup containing the matching exceptions rather than the original whole group.
Output
Ready to run.
Several except* handlers can run
Ordinary
except handling selects at most one matching handler. With
except*, different handlers can each receive the subgroup that matches their type, so more than one handler can execute for one exception group.
Output
Ready to run.
Unmatched exceptions continue propagating
An
except* handler does not automatically swallow exceptions it does not match. Any unmatched part of the group continues out of the try statement and can be handled by an outer ordinary
except.
Output
Ready to run.
Nested groups keep their structure
Exception groups can contain other exception groups. Matching is recursive, so a matching subgroup can preserve the surrounding group structure while removing non-matching leaves.
Output
Ready to run.
A single exception can also meet except*
If ordinary code raises one exception instead of an exception group, a matching
except* handler still receives a group-shaped value. This keeps the handler interface consistent.
Output
Ready to run.
Rules worth remembering
The exception type in
except* is required;
except*: is invalid. You also cannot use
return,
break, or
continue in an
except* clause because matching is designed so independent handlers can run without one handler changing the control flow of another.
For the ordinary single-exception case, keep using the traditional
try/
except pattern taught in the Exceptions lesson. This lesson owns grouped failures and
except* handling.
Quick check
What can happen when an ExceptionGroup reaches several matching except* clauses?
try:
raise ExceptionGroup("mixed", [ValueError("a"), TypeError("b")])
except* ValueError:
print("value")
except* TypeError:
print("type")
Exception groups are most useful when independent failures need to travel together. The traditional
except remains the right tool when there is one ordinary exception to handle.
Continue with the Python Exception Groups quiz and the code-completion exercise when you are ready.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.