Sub topic 8
Handling errors across tasks
This chapter assumes you can write coroutines, start them with asyncio.run, and run them together with gather or a TaskGroup. It also assumes you know try/except. Here you will see how an exception in one task affects its siblings, and how to handle it.
What happens when a task fails
A task that raises an exception stores it. The exception comes back out when something awaits the task or reads task.result(). If nobody does either, Python logs "Task exception was never retrieved" when the task is garbage collected. A failure in a task you never awaited is easy to miss.
gather and TaskGroup handle failures differently, so you need to choose deliberately.
gather: first exception or all results
By default, gather raises the first exception to the caller. The other awaitables are not cancelled and keep running, but you lose their results. With return_exceptions=True, gather never raises for child failures. It puts each exception in the result list, in input order.
TaskGroup: cancel siblings and collect failures
When one task in a TaskGroup fails, the group cancels the remaining tasks. After they finish, it raises an ExceptionGroup holding every failure. You handle it with except*, which matches exceptions by type inside the group. TaskGroup and except* need Python 3.11 or later.
import asyncio
async def ok():
return 1
async def bad():
raise ValueError("boom")
async def main():
results = await asyncio.gather(ok(), bad(), return_exceptions=True)
print(results)
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(ok())
tg.create_task(bad())
except* ValueError as eg:
print("caught", len(eg.exceptions), "ValueError")
asyncio.run(main())The first part prints a list with 1 and the ValueError. The second part prints caught 1 ValueError.
Choosing between them
| Situation | Use |
|---|---|
| Failures are acceptable, and you want a result or an error for each input | `gather(..., return_exceptions=True)` |
| All tasks must succeed, and one failure should stop the rest | `TaskGroup` |
| You need the first error only and can tolerate leftover tasks | `gather` with default settings |
Common errors
- Using
except ValueErroraround aTaskGroup. The group raises anExceptionGroup, so a plainexcept ValueErrordoes not match. Useexcept*. - Not checking
gatherresults. Withreturn_exceptions=True, errors are silent unless you inspect each item withisinstance(item, Exception). - Catching too broadly inside a task. A bare
except Exceptionthat swallows errors hides them from the group, so it never cancels the siblings. - Swallowing
CancelledError. It is not an ordinary failure. If you catch it, re-raise it, or cancellation will not work.
Errors that you can recover from belong inside the task, in a try/except around the risky call. Errors that should stop the whole operation should propagate to the TaskGroup.
Exercise
A TaskGroup runs three tasks. One raises ValueError and another raises KeyError. Which except clause form catches both, and what does eg.exceptions contain?
Show answer
Use except* (ValueError, KeyError) as eg:, or two separate except* clauses. The group raises one ExceptionGroup containing both failures, so eg.exceptions holds the ValueError and the KeyError. The third task is cancelled if it was still running.
Exercise
You call await asyncio.gather(a(), b(), c(), return_exceptions=True). How do you find which of the three calls failed?
Show answer
The result list keeps input order. Loop over it and test each item with isinstance(item, BaseException). The index of a matching item identifies the failed call.