# asyncio 异常：gather 中未捕获 CancelledError

- **ID:** `python/asyncio-gather-exception-handling`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |

## 解决方案

1. **Use return_exceptions=True to handle exceptions gracefully** (90% 成功率)
   ```
   results = await asyncio.gather(task1, task2, return_exceptions=True)
for r in results:
    if isinstance(r, Exception):
        # handle
   ```
2. **Catch CancelledError explicitly in each coroutine** (85% 成功率)
   ```
   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** — If the task is cancelled externally, CancelledError may still be raised and not caught by a general except. (50% 失败率)
- **Using asyncio.shield() on all tasks** — shield() prevents cancellation but may cause tasks to run indefinitely if not managed. (40% 失败率)
