python runtime_error ai_generated true

asyncio 异常:gather 中未捕获 CancelledError

asyncio.exceptions.CancelledError: CancelledError not caught in gather

ID: python/asyncio-gather-exception-handling

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-08-18首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.9 active

根因分析

当使用 asyncio.gather() 且 return_exceptions=False(默认)时,一个任务中的异常会取消其他任务,并且 CancelledError 可能意外传播。

English

When using asyncio.gather() with return_exceptions=False (default), an exception in one task cancels others, and CancelledError may propagate unexpectedly.

generic

解决方案

  1. 90% 成功率 Use return_exceptions=True to handle exceptions gracefully
    results = await asyncio.gather(task1, task2, return_exceptions=True)
    for r in results:
        if isinstance(r, Exception):
            # handle
  2. 85% 成功率 Catch CancelledError explicitly in each coroutine
    async def safe_coro():
        try:
            await something()
        except asyncio.CancelledError:
            # cleanup and re-raise if needed
            raise

无效尝试

常见但无效的做法:

  1. Wrapping each task in try-except without re-raising 50% 失败

    If the task is cancelled externally, CancelledError may still be raised and not caught by a general except.

  2. Using asyncio.shield() on all tasks 40% 失败

    shield() prevents cancellation but may cause tasks to run indefinitely if not managed.