# asyncio 异常：任务中引发了 CancelledError

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

## 根因

任务被外部取消（例如通过 task.cancel()），且未处理取消操作，导致其传播。

## 版本兼容性

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

## 解决方案

1. **Catch CancelledError and perform cleanup, then re-raise** (90% 成功率)
   ```
   try:
    await long_running_coro()
except asyncio.CancelledError:
    # cleanup resources
    raise
   ```
2. **Use asyncio.shield() to protect critical sections** (85% 成功率)
   ```
   await asyncio.shield(critical_coro())
   ```

## 无效尝试

- **Catching all exceptions except CancelledError** — CancelledError is a subclass of BaseException, so it may not be caught by except Exception. (70% 失败率)
- **Ignoring cancellation and continuing execution** — The event loop may be shutting down, and ignoring cancellation can cause resource leaks or hangs. (50% 失败率)
