python
runtime_error
ai_generated
true
asyncio 异常:gather 中未捕获 CancelledError
asyncio.exceptions.CancelledError: CancelledError not caught in gather
ID: python/asyncio-gather-exception-handling
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.
解决方案
-
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 -
85% 成功率 Catch CancelledError explicitly in each coroutine
async def safe_coro(): try: await something() except asyncio.CancelledError: # cleanup and re-raise if needed raise
无效尝试
常见但无效的做法:
-
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.
-
Using asyncio.shield() on all tasks
40% 失败
shield() prevents cancellation but may cause tasks to run indefinitely if not managed.