python
runtime_error
ai_generated
true
asyncio.exceptions.CancelledError: CancelledError raised in task
ID: python/asyncio-task-cancellation-error
80%Fix Rate
86%Confidence
0Evidence
2025-06-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
Root Cause
A task was cancelled externally (e.g., via task.cancel()), and the cancellation was not handled, causing it to propagate.
generic中文
任务被外部取消(例如通过 task.cancel()),且未处理取消操作,导致其传播。
Workarounds
-
90% success Catch CancelledError and perform cleanup, then re-raise
try: await long_running_coro() except asyncio.CancelledError: # cleanup resources raise -
85% success Use asyncio.shield() to protect critical sections
await asyncio.shield(critical_coro())
Dead Ends
Common approaches that don't work:
-
Catching all exceptions except CancelledError
70% fail
CancelledError is a subclass of BaseException, so it may not be caught by except Exception.
-
Ignoring cancellation and continuing execution
50% fail
The event loop may be shutting down, and ignoring cancellation can cause resource leaks or hangs.