Python asyncio Cheat Sheet/Collect exceptions with gather

Keep other tasks running even if one fails.

Section: Tasks and Concurrency

Collect exceptions with gather

python
python
import asyncio

async def ok():
    await asyncio.sleep(0.1)
    return "ok"

async def bad():
    await asyncio.sleep(0.1)
    raise ValueError("boom")

async def main():
    results = await asyncio.gather(ok(), bad(), return_exceptions=True)
    print(results)

asyncio.run(main())
Explanation

With `return_exceptions=True`, exceptions are returned in the result list instead of being raised immediately.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Tasks and Concurrency
Run tasks concurrently with gather
Wait for multiple coroutines and collect results.
OpenIn sheetpythonsame section
Create a background task
Schedule a coroutine to run concurrently.
OpenIn sheetpythonsame section
Use TaskGroup for structured concurrency
Run related tasks under a context manager.
OpenIn sheetpythonsame section
Wait until the first task completes
Use `asyncio.wait()` to control waiting behavior.
OpenIn sheetpythonsame section
Consume results as tasks finish
Process faster tasks first using `as_completed()`.
OpenIn sheetpythonsame section
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.