Sub topic 9
Handling failures with ExceptionGroup and except*
This chapter assumes you know the TaskGroup basics from the previous chapters: async with asyncio.TaskGroup(), create_task, and how a failing task cancels its siblings. It also assumes Python 3.11 or newer, because ExceptionGroup and except* were added in that release.
Why one exception is not enough
A normal try statement handles one exception at a time. A task group runs several tasks at once, and more than one of them can fail before the group finishes shutting down. Raising only the first error would hide the others. Python therefore raises a single ExceptionGroup that holds all of the errors.
What an ExceptionGroup is
An ExceptionGroup is an exception that wraps a list of other exceptions. It takes a message and a non-empty sequence of exceptions:
eg = ExceptionGroup("batch", [ValueError("a"), TypeError("b")])
print(eg.message)
print(eg.exceptions)Three attributes matter in practice:
messageis the text you gave it.exceptionsis a tuple of the wrapped exceptions.- Groups can nest, because a group is itself an exception and can sit inside another group.
If any wrapped exception derives from BaseException but not from Exception (for example KeyboardInterrupt), Python creates a BaseExceptionGroup instead. TaskGroup follows the same rule. For ordinary errors you will see ExceptionGroup.
What a TaskGroup raises
When the async with block exits, the group has already cancelled any unfinished siblings and waited for them to finish. It then raises one ExceptionGroup with the message "unhandled errors in a TaskGroup". The group contains:
- The exception from every task that failed.
- Any exception raised by the body of the
async withblock itself.
The CancelledError the group sends to siblings is not reported. That cancellation is the group's own doing, so it is not treated as a failure.
import asyncio
async def boom():
await asyncio.sleep(0.1)
raise ValueError("boom")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(boom())
except ValueError:
print("never reached")
except ExceptionGroup as eg:
print(type(eg).__name__, eg.exceptions)
asyncio.run(main())This prints ExceptionGroup (ValueError('boom'),). The except ValueError clause does not run. Even a single failure arrives wrapped in a group.
Matching with except*
The except* clause matches by type, like except, but it works on the contents of a group. For each clause, Python extracts the wrapped exceptions that match the type, including those inside nested groups. It runs the handler with a new group containing only those matches. The handler's variable is always a group, even when exactly one exception matched.
The next example makes two tasks fail in the same event-loop iteration. An asyncio.Barrier releases both tasks together, so both raise before the group can cancel either one.
import asyncio
async def fail(barrier, exc):
await barrier.wait()
raise exc
async def main():
barrier = asyncio.Barrier(2)
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fail(barrier, ValueError("bad value")))
tg.create_task(fail(barrier, KeyError("missing")))
except* ValueError as eg:
print("values:", [repr(e) for e in eg.exceptions])
except* KeyError as eg:
print("keys:", [repr(e) for e in eg.exceptions])
asyncio.run(main())Both handlers run, one after the other, each receiving only its own part of the group. With plain except, only the first matching clause would run.
Rules for except*
- You cannot mix
exceptandexcept*in onetrystatement. - You cannot use
return,break, orcontinueinside anexcept*block. Several handlers may run for one group, so a jump out of one would skip the others. - You cannot catch
ExceptionGrouporBaseExceptionGroupthemselves withexcept*. - A bare
raiseinside a handler re-raises only the exceptions that handler matched. - Raising a new exception inside a handler combines it with the other results into a new group.
Unmatched exceptions keep propagating
Exceptions that no clause matches are not lost. After all handlers run, Python re-raises a group containing whatever was left over. This lets you handle the failures you know about and pass the rest upward.
try:
try:
raise ExceptionGroup("g", [ValueError("v"), TypeError("t")])
except* ValueError:
print("handled the ValueError")
except* TypeError as eg:
print("outer caught:", repr(eg.exceptions[0]))The inner except* handles ValueError. A new group holding only the TypeError reaches the outer clause.
The table below compares the two statements.
| Aspect | `except` | `except*` |
|---|---|---|
| Input | One exception | An exception group (a bare exception is wrapped) |
| Handler variable | The matching exception | A group of the matching exceptions |
| Clauses that run | First match only | Every clause that matches something |
| Unmatched part | Propagates unchanged | Re-raised as a smaller group |
| `return` and `break` in handler | Allowed | Not allowed |
Inspecting groups: subgroup, split, and nesting
You can do the matching by hand with two methods:
subgroup(type)returns a group of the matching exceptions, orNoneif nothing matches.split(type)returns a pair: the matching part and the rest. Either can beNone.
Both keep the nesting structure and the original message. Because groups can nest, a small helper that walks the leaves is useful:
def leaves(group):
for e in group.exceptions:
if isinstance(e, BaseExceptionGroup):
yield from leaves(e)
else:
yield e
eg = ExceptionGroup("batch", [
ValueError("a"),
TypeError("b"),
ExceptionGroup("inner", [ValueError("c"), OSError("d")]),
])
match, rest = eg.split(ValueError)
print([repr(e) for e in leaves(match)])
print([repr(e) for e in leaves(rest)])The first line prints the two ValueError objects, a and c. The second prints TypeError('b') and OSError('d'). The match from the nested inner group stays inside a group named inner, so the shape of the original is preserved.
A flat TaskGroup rarely nests. Nested groups appear when one TaskGroup runs inside a task of another. The outer group then wraps the inner group in its own group, and except* still finds the leaves.
Choosing where to handle an error
Because one failure cancels every sibling, you have two design choices.
- Let the failure reach the group. Use this when the tasks form one unit of work, so a single failure makes the rest worthless. Handle the result once, outside the
async with, withexcept*. - Handle the failure inside the task. Use this when failures are expected and independent, such as one bad URL among many. The task catches its own error and returns it as a value, so the group never sees a failure and no sibling is cancelled.
import asyncio
async def fetch(n):
await asyncio.sleep(0.1 * n)
if n == 2:
raise ConnectionError("n=2 failed")
return n
async def attempt(n):
try:
return n, await fetch(n)
except ConnectionError as exc:
return n, exc
async def main():
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(attempt(n)) for n in (1, 2, 3)]
print([t.result() for t in tasks])
asyncio.run(main())All three tasks finish. The result for task 2 is the exception object instead of a number, and the caller decides what to do with it.
Common mistakes
- Writing
except Exceptionaround a TaskGroup. It does catch the group, becauseExceptionGroupderives fromException. You then lose the type-based matching and must unpack.exceptionsyourself. - Reading
eg.exceptions[0]as "the error". It is only the first of possibly several, and its order depends on timing. - Reading
task.result()after a failure. Cancelled tasks raiseCancelledErrorfromresult(). Read results only on the success path, after the block exits without an exception. - Forgetting that
except*handlers can all run. Do not put cleanup in one handler and assume another handler did not also run.
Exercises
Exercise
A TaskGroup runs one task, and that task raises RuntimeError("x"). The code is wrapped in try: ... except RuntimeError:. Does the handler run? What should you write instead?
Show answer
No. The TaskGroup raises an ExceptionGroup that contains the RuntimeError, even when only one task failed, and except RuntimeError does not match a group. Use except* RuntimeError as eg:. The variable eg is a group, so read the error with eg.exceptions[0].
Exercise
Given eg = ExceptionGroup("g", [ValueError("a"), KeyError("b"), TypeError("c")]), a try has except* ValueError: and except* KeyError: clauses and nothing else. What happens when eg is raised inside it?
Show answer
Both handlers run, each with its own matching part. The TypeError matches no clause, so Python re-raises an ExceptionGroup("g", [TypeError("c")]) after the handlers finish. The caller sees that smaller group.
Exercise
Why is return not allowed inside an except* block?
Show answer
One raised group can trigger several except* clauses. A return (or break or continue) in one handler would skip the remaining handlers and leave part of the group unprocessed. The language rule rules this out, so every matching clause is guaranteed to get its turn.