python
runtime_error
ai_generated
true
asyncio.exceptions.CancelledError:
ID: python/asyncio-cancellederror-not-handled
80%修复率
86%置信度
0证据数
2024-05-21首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8+ | active | — | — | — |
| 3.9+ | active | — | — | — |
| 3.10+ | active | — | — | — |
| 3.11+ | active | — | — | — |
| 3.12+ | active | — | — | — |
根因分析
某个任务被取消(超时、关闭或父任务取消),CancelledError 未被捕获并传播,通常被记录为未处理的任务异常。
English
A task was cancelled (timeout, shutdown, or parent cancellation) and the CancelledError propagated uncaught, often logged as an unhandled task exception.
解决方案
-
95% 成功率
try: await long_running() except asyncio.CancelledError: await cleanup() raise -
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
无效尝试
常见但无效的做法:
-
85% 失败
Swallowing cancellation breaks structured concurrency; the parent expects the task to stop.
-
80% 失败
Shield everywhere defeats cancellation and leaves tasks running after shutdown.