# asyncio.exceptions.CancelledError: 

- **ID:** `python/asyncio-cancellederror-not-handled`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

某个任务被取消（超时、关闭或父任务取消），CancelledError 未被捕获并传播，通常被记录为未处理的任务异常。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8+ | active | — | — |
| 3.9+ | active | — | — |
| 3.10+ | active | — | — |
| 3.11+ | active | — | — |
| 3.12+ | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   try:
    await long_running()
except asyncio.CancelledError:
    await cleanup()
    raise
   ```
2. **** (90% 成功率)
   ```
   tasks = [asyncio.create_task(w(i)) for i in range(5)]
try:
    await asyncio.gather(*tasks)
except asyncio.CancelledError:
    for t in tasks:
        t.cancel()
    raise
   ```

## 无效尝试

- **** — Swallowing cancellation breaks structured concurrency; the parent expects the task to stop. (85% 失败率)
- **** — Shield everywhere defeats cancellation and leaves tasks running after shutdown. (80% 失败率)
