python
runtime_error
ai_generated
true
asyncio.exceptions.CancelledError: Task was cancelled
ID: python/asyncio-task-cancellation-not-handled
80%Fix Rate
87%Confidence
0Evidence
2024-03-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
Root Cause
A coroutine that is cancelled while awaiting an operation does not handle CancelledError, causing the task to terminate abruptly and potentially leaving resources unclean.
generic中文
协程在等待操作时被取消,但未处理 CancelledError,导致任务突然终止并可能使资源未清理。
Workarounds
-
95% success
try: await long_operation() except asyncio.CancelledError: # cleanup resources raise # re-raise to acknowledge cancellation -
80% success
result = await asyncio.shield(critical_operation())
Dead Ends
Common approaches that don't work:
-
70% fail
Ignoring cancellation can violate asyncio's cooperative cancellation model and lead to tasks that never truly cancel.
-
40% fail
Finally runs but the exception propagates; if not caught, it may still terminate the task.