Sub topic 15
Exception groups and except* (Python 3.11+)
This chapter covers the one part of Python's exception system that works differently from the rest: raising and handling several unrelated errors at once. It assumes you know try/except, the exception hierarchy, raise, and raise from. It also assumes you can write a small class that inherits from another class. You need Python 3.11 or later to run the examples.
Why one exception is not always enough
A normal raise carries exactly one exception. That is fine for sequential code, because the first failure stops everything. Concurrent code is different. If you start ten tasks and three fail, one exception cannot describe what happened, and the other two errors would be lost.
Python 3.11 added two things for this case:
ExceptionGroup, an exception that wraps a list of other exceptions.- The
except*clause, which handles the members of a group by type.
The main users today are asyncio.TaskGroup and libraries that run work in parallel and collect failures. You will rarely raise groups by hand in everyday code, but you will need to catch them.
Building and inspecting an ExceptionGroup
An ExceptionGroup takes a message and a non-empty sequence of exceptions.
eg = ExceptionGroup("batch failed", [ValueError("a"), TypeError("b")])
print(eg.message)
print(eg.exceptions)
print(eg)The attributes are:
messageis the description you passed in.exceptionsis a tuple of the wrapped exceptions.str(eg)shows the message and the number of sub-exceptions, for examplebatch failed (2 sub-exceptions).
The wrapped exceptions can themselves be groups, so groups nest. A group is also an ordinary exception: it has a traceback, can be chained with raise from, and can be caught by name.
ExceptionGroup accepts only subclasses of Exception. To wrap something like KeyboardInterrupt, use BaseExceptionGroup. If every member of a BaseExceptionGroup is an Exception, Python creates an ExceptionGroup automatically. An empty list raises ValueError.
Handling members with except*
An except* clause matches members of the group by type and gives you a new group containing only the matches.
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}")This prints:
value errors: (ValueError('a'),)
type errors: (TypeError('b'),)Two differences from plain except matter here.
First, except* clauses do not compete. With plain except, the first matching clause runs and the rest are skipped. With except*, every clause that matches something in the group runs, each with its own slice of the members.
Second, the name after as is always a group, even when only one error matched. Write eg.exceptions or loop over it. Do not treat it as a single exception.
If a plain exception (not a group) is raised and except* matches it, Python wraps it in an ExceptionGroup with an empty message before your handler sees it. Your handler code therefore works the same either way.
What happens to members nobody handles
Members that no clause matches are not lost. After all clauses run, Python raises a new group containing the unhandled members. It keeps the original message and traceback information.
try:
try:
raise ExceptionGroup("batch", [ValueError("a"), KeyError("k")])
except* ValueError as eg:
print("inner handled", eg.exceptions)
except* KeyError as eg:
print("outer handled", eg.exceptions)The inner handler takes the ValueError. The KeyError leaves the inner try inside a new group and is caught by the outer clause. If nothing caught it, the program would end with a traceback showing the remaining group.
Splitting groups without try
Sometimes you want to sort a group without a try statement, for example to log one kind of error and forward the rest. Groups have two methods for this:
subgroup(condition)returns a group of the matching members, orNoneif nothing matches.split(condition)returns a pair(match, rest). Either may beNone.
eg = ExceptionGroup("batch", [ValueError("a"), TypeError("b"), ValueError("c")])
match, rest = eg.split(ValueError)
print(match.exceptions)
print(rest.exceptions)
print(eg.subgroup(KeyError))Output:
(ValueError('a'), ValueError('c'))
(TypeError('b'),)
NoneThe condition can be an exception type, a tuple of types, or a function that takes an exception and returns a boolean. The returned groups keep the original message, traceback, and chaining information, so they still look like parts of the original failure. For nested groups, the methods keep the nesting shape and drop any sub-group that ends up empty.
A realistic example with TaskGroup
asyncio.TaskGroup is the most common source of exception groups. If any task in the group fails, the group cancels the others and raises an ExceptionGroup when the async with block exits.
import asyncio
async def fetch(n):
if n % 2:
raise ValueError(f"bad input {n}")
return n
async def main():
try:
async with asyncio.TaskGroup() as tg:
for n in range(4):
tg.create_task(fetch(n))
except* ValueError as eg:
for exc in eg.exceptions:
print("failed:", exc)
asyncio.run(main())This prints failed: bad input 1 and failed: bad input 3. The order follows the order in which the tasks failed, so do not rely on it. Notice the failure is a group even if only one task fails. Code that used except ValueError around a TaskGroup will stop working, because a plain except ValueError does not match a group that contains a ValueError.
Rules and restrictions
Python enforces several rules at compile time, so mistakes show up as SyntaxError before the program runs.
| Rule | Why it exists |
|---|---|
| You cannot mix `except` and `except*` in one `try` statement. | The two forms have different matching semantics. |
| A bare `except*:` is not allowed. You must name a type. | Handling everything silently would hide group members. |
| You cannot write `except* ExceptionGroup`. | `except*` splits groups, so catching the group type itself makes no sense. |
| `return`, `break`, and `continue` are not allowed inside an `except*` block. | They would end the block early and leave the other members' handling unclear. |
Inside an except* block, a bare raise re-raises the matched members. Raising a new exception adds it to the groups that propagate, and Python combines it with any unhandled members. The new exception is chained to the one being handled, as with raise from.
Choosing between except and except*
Use except* when the code you call can raise a group: a TaskGroup, a library that documents groups, or your own code that collects errors. Use plain except everywhere else. Using except* on code that raises single exceptions works, because Python wraps them. It makes your handler bodies more awkward, though, because every name is a group.
If you write a function that collects errors, raise an ExceptionGroup only at the end, after all work is finished or cancelled. Use a clear message such as the operation name, and keep each member's original traceback.
Exercise
A function runs three checks and raises ExceptionGroup("checks", [ValueError("x"), KeyError("y"), ValueError("z")]). You wrap the call in a try with except* ValueError as eg: that prints len(eg.exceptions), and no other clause. What does the handler print, and what happens to the KeyError?
Show answer
The handler prints 2, because eg is a new group holding only the two ValueError members. The KeyError is not matched, so after the handler finishes Python raises a new ExceptionGroup("checks", ...) containing just the KeyError. It propagates to the caller, and if nothing catches it the program ends with a traceback.
Exercise
This code raises a SyntaxError. Give two separate reasons.
try:
run()
except* ValueError:
return None
except KeyError:
pass
Show answer
First, except* and except are mixed in one try statement, which is not allowed. Second, return is used inside an except* block, which is also not allowed. Fix it by using except* for both types and moving the return outside the try statement, for example by setting a variable in the handler and returning it afterwards.
Exercise
Given eg = ExceptionGroup("g", [OSError("disk"), ValueError("v")]), what do eg.subgroup(OSError) and eg.split(KeyError) return?
Show answer
eg.subgroup(OSError) returns a new ExceptionGroup with the message "g" containing only the OSError. eg.split(KeyError) returns (None, eg_like): nothing matches, so the first value is None, and the second is a group with all the original members (a group with the same message and both exceptions).