python
runtime_error
ai_generated
true
asyncio.exceptions.CancelledError:
ID: python/asyncio-cancellederror
80%修复率
88%置信度
0证据数
2024-09-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
任务被取消(例如由 asyncio.wait_for 超时或外部取消触发),CancelledError 在用户代码中传播,未在清理后重新抛出。
English
A task was cancelled (e.g. by asyncio.wait_for timeout or an outer cancellation), and the CancelledError propagated up through user code without being re-raised after cleanup.
解决方案
-
95% 成功率
Run cleanup then re-raise: try: await work() except asyncio.CancelledError: await cleanup() raise -
90% 成功率
Use contextlib.suppress(asyncio.CancelledError) only around cleanup awaits, never around the main work.
-
85% 成功率
Use asyncio.shield() around critical sections that must not be cancelled.
无效尝试
常见但无效的做法:
-
90% 失败
In 3.8+ CancelledError inherits from BaseException, so this doesn't catch it anyway; and catching it silently breaks cancellation semantics.
-
85% 失败
Swallows cancellation, leaving parent tasks hanging and breaking structured concurrency.
-
80% 失败
Re-cancelling without re-raising still doesn't propagate cancellation up the stack.