python runtime_error ai_generated true

asyncio.exceptions.CancelledError:

ID: python/asyncio-cancellederror-not-caught

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 92% success
    try:
        await work()
    except asyncio.CancelledError:
        await cleanup()
        raise  # always re-raise
  2. 85% success
    try:
        await asyncio.shield(flush_buffer())
    except asyncio.CancelledError:
        raise

Dead Ends

Common approaches that don't work:

  1. 90% fail

    CancelledError is a BaseException in 3.8+, so except Exception does not catch it.

  2. 80% fail

    Prevents proper cancellation propagation, causing hangs on shutdown and resource leaks.