# asyncio.exceptions.CancelledError: 

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

## 根因

任务被取消（例如由 asyncio.wait_for 超时或外部取消触发），CancelledError 在用户代码中传播，未在清理后重新抛出。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Run cleanup then re-raise:

try:
    await work()
except asyncio.CancelledError:
    await cleanup()
    raise
   ```
2. **** (90% 成功率)
   ```
   Use contextlib.suppress(asyncio.CancelledError) only around cleanup awaits, never around the main work.
   ```
3. **** (85% 成功率)
   ```
   Use asyncio.shield() around critical sections that must not be cancelled.
   ```

## 无效尝试

- **** — In 3.8+ CancelledError inherits from BaseException, so this doesn't catch it anyway; and catching it silently breaks cancellation semantics. (90% 失败率)
- **** — Swallows cancellation, leaving parent tasks hanging and breaking structured concurrency. (85% 失败率)
- **** — Re-cancelling without re-raising still doesn't propagate cancellation up the stack. (80% 失败率)
