python
runtime_error
ai_generated
true
asyncio.exceptions.CancelledError:
ID: python/asyncio-cancellederror
80%Fix Rate
88%Confidence
0Evidence
2024-09-11First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
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.
generic中文
任务被取消(例如由 asyncio.wait_for 超时或外部取消触发),CancelledError 在用户代码中传播,未在清理后重新抛出。
Workarounds
-
95% success
Run cleanup then re-raise: try: await work() except asyncio.CancelledError: await cleanup() raise -
90% success
Use contextlib.suppress(asyncio.CancelledError) only around cleanup awaits, never around the main work.
-
85% success
Use asyncio.shield() around critical sections that must not be cancelled.
Dead Ends
Common approaches that don't work:
-
90% fail
In 3.8+ CancelledError inherits from BaseException, so this doesn't catch it anyway; and catching it silently breaks cancellation semantics.
-
85% fail
Swallows cancellation, leaving parent tasks hanging and breaking structured concurrency.
-
80% fail
Re-cancelling without re-raising still doesn't propagate cancellation up the stack.