# asyncio.exceptions.CancelledError：任务被取消

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

## 根因

协程在等待操作时被取消，但未处理 CancelledError，导致任务突然终止并可能使资源未清理。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   try:
    await long_operation()
except asyncio.CancelledError:
    # cleanup resources
    raise  # re-raise to acknowledge cancellation
   ```
2. **** (80% 成功率)
   ```
   result = await asyncio.shield(critical_operation())
   ```

## 无效尝试

- **** — Ignoring cancellation can violate asyncio's cooperative cancellation model and lead to tasks that never truly cancel. (70% 失败率)
- **** — Finally runs but the exception propagates; if not caught, it may still terminate the task. (40% 失败率)
