Sub topic 15
Exception groups and except* (Python 3.11+)
This chapter assumes you know try/except, how handlers are matched against the exception hierarchy, and how raise works. It also needs Python 3.11 or later.
Why exception groups exist
A normal raise carries one exception. Some code runs several operations at once, such as concurrent tasks or a batch of validations. Several of them can fail at the same time, and a single exception cannot report all of those failures.
Python 3.11 added ExceptionGroup. It wraps a message and a list of exceptions into one exception that you can raise and catch like any other. Its .exceptions attribute is a tuple of the members. Members can also be nested groups. asyncio.TaskGroup raises an ExceptionGroup when more than one task fails.
group = ExceptionGroup("batch failed", [ValueError("a"), TypeError("b")])
print(group.exceptions)ExceptionGroup accepts only members that are Exception subclasses. Use BaseExceptionGroup if a member might be something like KeyboardInterrupt.
Handling members with except*
The except* clause matches against the members of a group, not the group itself. Each clause receives a new group that contains only the members it matched.
try:
raise ExceptionGroup("batch failed", [ValueError("a"), TypeError("b")])
except* ValueError as eg:
print(f"value errors: {eg.exceptions}")
except* TypeError as eg:
print(f"type errors: {eg.exceptions}")Unlike ordinary except, more than one except* clause can run for a single raise. Each clause takes the members it matches, and the remaining members go on to the next clause. The name after as is always a group, even if only one member matched.
Unmatched members keep propagating
If some members match no clause, Python re-raises them together in a new group. That group keeps the original message and traceback information.
try:
try:
raise ExceptionGroup("batch", [ValueError("a"), KeyError("k")])
except* ValueError as eg:
print(f"handled: {eg.exceptions}")
except ExceptionGroup as rest:
print(f"left over: {rest.exceptions}")This prints the ValueError first, then the leftover KeyError. The outer plain except works because the leftover is still an ExceptionGroup.
Rules and common errors
- You cannot mix
exceptandexcept*in the sametrystatement. Python reports aSyntaxError. - You cannot use
return,break, orcontinueinside anexcept*block. - You cannot write
except* ExceptionGroup. Anexcept*clause must name the member types it handles. - If the raised exception is not a group,
except*still matches it. It wraps the exception in anExceptionGroupwith an empty message, so theasname is always a group. - A bare
raiseinsideexcept*re-raises only the members that clause matched. The leftovers still propagate as usual.
Splitting a group manually
Groups also have methods for filtering without except*. subgroup(condition) returns a group of the matching members, or None if nothing matches. split(condition) returns a pair, the matching group and the rest. Each condition can be an exception type or a function.
group = ExceptionGroup("batch", [ValueError("a"), TypeError("b")])
matched, rest = group.split(ValueError)
print(matched.exceptions)
print(rest.exceptions)Exercise
A try statement raises ExceptionGroup("g", [ValueError("x"), KeyError("y")]) and has only one clause, except* ValueError. What happens to the KeyError?
Show answer
It is not matched, so it is re-raised after the clause finishes, inside a new ExceptionGroup with the original message "g". The caller sees an ExceptionGroup that contains only the KeyError.
Exercise
Why does this code fail to compile: a try block with except ValueError: followed by except* TypeError:?
Show answer
A single try statement cannot mix except and except*. Use one style for the whole statement.