Catch exception in asyncio gather
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
asyncio.gather() runs multiple coroutines concurrently and collects their results. By default, if any task raises an exception, gather cancels the remaining tasks and re-raises the first exception. The return_exceptions=True parameter changes this behavior to return exceptions as values in the result list instead of raising them.
Default Behavior (Raises Exceptions)
The first exception cancels other tasks and propagates up.
Using return_exceptions=True
With return_exceptions=True, exceptions are returned as values alongside successful results:
All tasks run to completion regardless of individual failures.
Handling Mixed Results
Per-Task Try/Except
Wrap individual coroutines for fine-grained error handling:
asyncio.gather vs TaskGroup (Python 3.11+)
Python 3.11 introduced TaskGroup as a structured alternative:
| Feature | asyncio.gather | asyncio.TaskGroup |
| Python version | 3.4+ | 3.11+ |
| Exception handling | First exception or return_exceptions | ExceptionGroup with except* |
| Cancellation | Cancels remaining on first error | Cancels remaining on first error |
| Structured concurrency | No | Yes |
Timeout with gather
Combining gather with Semaphore
Limit concurrency when gathering many tasks:
Common Pitfalls
- Task Continuation: With
return_exceptions=True, even if one task fails, others proceed and complete, potentially returning either results or exceptions. This is the whole point — but check each result individually. - Careful Inspection: When using
return_exceptions=True, carefully inspect the result list to handle exceptions appropriately, as they are part of the output. Useisinstance(result, Exception)to detect failures. - Performance Impact: Proper error handling encourages better performance and reliability, especially in web servers or applications making diverse network calls.
- Cancellation propagation: Without
return_exceptions=True, the first exception causesgatherto cancel remaining tasks. Cancelled tasks raiseCancelledError, which may mask the original exception. - Fire and forget: Creating tasks with
asyncio.gatherand not awaiting the result means exceptions are silently lost. Always awaitgather. - Exception types:
return_exceptions=Truereturns all exception types, includingCancelledError. Filter appropriately if you need to distinguish cancellation from real errors.
Summary
- By default,
asyncio.gatherre-raises the first exception and cancels remaining tasks - Use
return_exceptions=Trueto collect all results (successes and exceptions) without cancellation - Check results with
isinstance(result, Exception)to separate successes from failures - Use
TaskGroup(Python 3.11+) for structured concurrency withexcept*handling - Wrap individual coroutines in try/except for per-task error handling without
return_exceptions

