python
runtime_error
ai_generated
true
asyncio.exceptions.CancelledError:
ID: python/asyncio-cancellederror-not-caught
80%Fix Rate
88%Confidence
0Evidence
2024-05-21First 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 (via task.cancel() or a timeout), and the coroutine did not propagate or handle CancelledError, which in Python 3.8+ inherits from BaseException, not Exception.
generic中文
任务被取消(通过 task.cancel() 或超时),而协程未传播或处理 CancelledError;在 Python 3.8+ 中它继承自 BaseException 而非 Exception。
Workarounds
-
92% success
try: await work() except asyncio.CancelledError: await cleanup() raise # always re-raise -
85% success
try: await asyncio.shield(flush_buffer()) except asyncio.CancelledError: raise
Dead Ends
Common approaches that don't work:
-
90% fail
CancelledError is a BaseException in 3.8+, so except Exception does not catch it.
-
80% fail
Prevents proper cancellation propagation, causing hangs on shutdown and resource leaks.