python runtime_error ai_generated true

asyncio.exceptions.CancelledError:

ID: python/asyncio-cancellederror-not-handled

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%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 (timeout, shutdown, or parent cancellation) and the CancelledError propagated uncaught, often logged as an unhandled task exception.

generic

中文

某个任务被取消(超时、关闭或父任务取消),CancelledError 未被捕获并传播,通常被记录为未处理的任务异常。

Workarounds

  1. 95% success
    try:
        await long_running()
    except asyncio.CancelledError:
        await cleanup()
        raise
  2. 90% success
    tasks = [asyncio.create_task(w(i)) for i in range(5)]
    try:
        await asyncio.gather(*tasks)
    except asyncio.CancelledError:
        for t in tasks:
            t.cancel()
        raise

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Swallowing cancellation breaks structured concurrency; the parent expects the task to stop.

  2. 80% fail

    Shield everywhere defeats cancellation and leaves tasks running after shutdown.