Sub topic 9
Handling failures with ExceptionGroup and except*
This chapter assumes you know how asyncio.TaskGroup starts and waits for tasks, and that you are comfortable with try/except.
Why a group of errors
Several tasks in a TaskGroup can fail at about the same time. A normal raise carries one exception, so Python 3.11 added ExceptionGroup, an exception that holds a list of other exceptions. When any task in a group fails, the group cancels its siblings, waits for them to finish, and raises an ExceptionGroup with every failure it collected.
A single failure is still a group
import asyncio
async def slow():
try:
await asyncio.sleep(10)
finally:
print("slow: cleaned up")
async def broken():
await asyncio.sleep(0.1)
raise ValueError("something went wrong")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(slow())
tg.create_task(broken())
except* ValueError as eg:
print("caught:", eg.exceptions)
asyncio.run(main())The output is slow: cleaned up, then caught: (ValueError('something went wrong'),). The slow task is cancelled and runs its finally block before the group raises.
The group wraps the ValueError even though only one task failed. A plain except ValueError would not catch it, because the exception that arrives is an ExceptionGroup, not a ValueError.
How except* works
An except* clause matches the exceptions inside the group by type. It receives a new group, bound to the name after as, that contains only the matching exceptions. Its .exceptions attribute is a tuple.
Unlike ordinary except, several except* clauses can run for one raised group. Each clause takes its share. Anything left unmatched is raised again when the try statement ends.
import asyncio
async def bad_value():
raise ValueError("bad value")
async def bad_key():
raise KeyError("missing")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(bad_value())
tg.create_task(bad_key())
except* ValueError as eg:
print("values:", [str(e) for e in eg.exceptions])
except* KeyError as eg:
print("keys:", [repr(e) for e in eg.exceptions])
asyncio.run(main())Both tasks fail on their first step, so both errors are collected. The output is values: ['bad value'], then keys: ["KeyError('missing')"].
Common errors
- Using plain
exceptfor task errors. It misses the group. Useexcept*, or catchExceptionGroupand inspect it yourself. - Mixing
exceptandexcept*in onetrystatement. Python rejects this with aSyntaxError. - Using
return,break, orcontinueinside anexcept*block. These are also aSyntaxError. - Expecting every task's error. Tasks that were cancelled because of the first failure add no error of their own, so the group holds only the real failures.
- Forgetting nesting. Groups can contain groups.
except*searches the whole tree, buteg.exceptionson a caught group lists only its direct members.
Exercise
A TaskGroup runs three tasks. One raises ValueError and another raises TypeError. Your code has only except* ValueError. What happens to the TypeError?
Show answer
The except* ValueError clause handles only the ValueError. The TypeError is not matched, so it is raised again in a new ExceptionGroup when the try statement ends, and the caller must handle it or the program fails.