Sub topic 8
Handling errors across tasks
This chapter assumes you can write coroutines, start them with asyncio.run, and create tasks. It also assumes you know try/except and that gather and TaskGroup run work concurrently. Python 3.11 or later is needed for TaskGroup and except*.
Errors in concurrent code differ from errors in sequential code because several operations can fail at once. A failed task also has no caller waiting on it, unless you arrange one. This chapter covers where exceptions go, what happens to sibling tasks, and how to pick a strategy.
Where an exception goes
An exception raised inside a coroutine that you await directly travels up to the caller, as in ordinary code. Once the coroutine is wrapped in a task, the exception is stored on the task object. It is re-raised in whichever code awaits the task, or returned by task.exception().
If nobody awaits the task or reads its exception, Python logs Task exception was never retrieved when the task is garbage collected. The error is not lost, but it surfaces late and far from its cause. Most error handling in asyncio is about making sure someone retrieves each exception.
gather: the default behavior
asyncio.gather raises the first exception it sees and does not cancel the other awaitables.
import asyncio
async def slow():
await asyncio.sleep(0.2)
print("slow finished")
async def bad():
raise ValueError("boom")
async def main():
try:
await asyncio.gather(slow(), bad())
except ValueError as e:
print("caught", e)
await asyncio.sleep(0.5)
asyncio.run(main())This prints caught boom first, then slow finished. The slow task keeps running after gather has already raised. If main returned right after the except block, asyncio.run would cancel slow. In a long-running program, slow would finish unobserved and its result would be discarded.
Two more consequences follow. When several awaitables fail, you see only the first exception, and the later ones are not reported. Also, the result list is all-or-nothing: once gather raises, you do not receive the results of the successful calls.
gather with return_exceptions=True
Pass return_exceptions=True to get one entry per input, in input order. A failed call puts its exception object in that slot.
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)
for r in results:
if isinstance(r, Exception):
print("failed:", repr(r))
else:
print("ok:", r)
asyncio.run(main())You must inspect each entry yourself. A common mistake is to treat the list as results and pass an exception object to code that expects a number. Test with isinstance(r, Exception). If you also need to detect cancellation, test for BaseException, because CancelledError is not an Exception subclass.
TaskGroup: fail together
A TaskGroup ties the lifetime of its tasks to the async with block. If any task raises, the group cancels the remaining tasks, waits for them to finish, and then raises an ExceptionGroup containing every real failure. Tasks that were merely cancelled as a result are not included.
import asyncio
async def slow():
try:
await asyncio.sleep(5)
except asyncio.CancelledError:
print("slow cancelled")
raise
async def bad(msg):
raise ValueError(msg)
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(slow())
tg.create_task(bad("first"))
tg.create_task(bad("second"))
except* ValueError as eg:
for exc in eg.exceptions:
print("ValueError:", exc)
asyncio.run(main())The output is slow cancelled, ValueError: first, ValueError: second. Both bad tasks raise on their first step, which runs in the same loop iteration, so both failures are collected. If the second task had awaited something first, the group would probably have cancelled it before it could fail, and you would see one error.
The same happens if the body of the async with block raises. The group cancels all its tasks and the exception joins the group.
Handling an ExceptionGroup with except*
except* matches by type against the members of the group. The name bound after as is a new ExceptionGroup holding only the matching exceptions. You can write several except* clauses, and each exception is handled by the first clause that matches. Unmatched exceptions are re-raised in a new group.
import asyncio
async def fail(exc):
raise exc
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fail(ValueError("bad value")))
tg.create_task(fail(KeyError("missing")))
except* ValueError as eg:
print("value errors:", [str(e) for e in eg.exceptions])
except* KeyError as eg:
print("key errors:", [repr(e) for e in eg.exceptions])
asyncio.run(main())A plain except ValueError: will not catch a ValueError that arrives inside an ExceptionGroup. This is the most common migration bug when switching from gather to TaskGroup. You also cannot mix except and except* in the same try statement.
Failures that should not cancel siblings
Sometimes one failed item should not stop the rest, for example when fetching 50 independent URLs. You have two options. Use gather(..., return_exceptions=True), or wrap each unit of work so it handles its own errors inside a TaskGroup.
import asyncio
async def fetch(n):
if n == 2:
raise ConnectionError(f"item {n} unreachable")
await asyncio.sleep(0.1)
return n * 10
async def safe(n):
try:
return await fetch(n)
except ConnectionError as e:
print("skipping:", e)
return None
async def main():
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(safe(n)) for n in range(4)]
print([t.result() for t in tasks])
asyncio.run(main())This prints the skip message and then [0, 10, None, 30]. The wrapper catches only the errors you expect. Anything else still reaches the group and cancels the siblings.
Fire-and-forget tasks
A task created with asyncio.create_task and never awaited has no one to receive its exception. Keep a reference to the task, because the loop holds only a weak reference to it. Attach a done callback that reads the outcome.
import asyncio
async def job():
raise RuntimeError("job failed")
def report(task):
if task.cancelled():
return
exc = task.exception()
if exc is not None:
print("background task failed:", repr(exc))
async def main():
task = asyncio.create_task(job())
task.add_done_callback(report)
await asyncio.sleep(0.1)
asyncio.run(main())Check task.cancelled() before calling task.exception(). Calling exception() on a cancelled task raises CancelledError. Reading the exception also marks it as retrieved, so Python will not log the warning.
Choosing a strategy
| Need | Tool | Behavior on failure |
|---|---|---|
| All-or-nothing work, with cleanup of siblings | `TaskGroup` | Cancels siblings, raises `ExceptionGroup` |
| Collect every outcome, good or bad | `gather(return_exceptions=True)` | Exceptions appear as values in the result list |
| Quick fail, siblings left running (rarely wanted) | `gather()` | Raises the first exception only |
| Background work with no waiter | `create_task` plus a done callback | You report the error yourself |
Prefer TaskGroup for new code that runs on 3.11 or later. It reports every failure and leaves no stray tasks behind. Use return_exceptions=True when partial results matter more than stopping early.
Common errors
- Catching the wrong type. Writing
except ValueErroraround aTaskGroupmisses grouped errors. Useexcept*. - Ignoring
return_exceptionsresults. Failures sit silently in the list until something uses them as data. - Dropping task references. An unreferenced task can be garbage collected before it finishes, and its error is reported late.
- Swallowing
CancelledError. Re-raise it after cleanup. - Catching too broadly inside a
TaskGroup. A blanketexcept Exceptionin each task hides failures that should stop the group.
Exercise
A TaskGroup runs three tasks. Task A raises ValueError after 0.1 seconds, task B would take 5 seconds, and task C raises KeyError after 0.3 seconds. Which exceptions does the ExceptionGroup contain, and why?
Show answer
Only the ValueError from task A. When A fails, the group cancels B and C. B ends as cancelled, which is not reported as a failure. C is cancelled at 0.1 seconds, before its KeyError would be raised at 0.3 seconds. So the group holds one ValueError, and except* ValueError catches it. A plain except ValueError would not, because the error is wrapped in the group.
Exercise
You call results = await asyncio.gather(f(), g(), h(), return_exceptions=True). How do you tell which calls failed, and what type check should you use if you also want to detect cancelled calls?
Show answer
Results are in input order, so results[0] belongs to f(), and so on. Loop over them and test each entry with isinstance(r, BaseException). isinstance(r, Exception) finds ordinary failures but misses CancelledError, which is a BaseException.