python runtime_error ai_generated true

asyncio.exceptions.CancelledError:

ID: python/asyncio-cancellederror-not-caught

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-05-21首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

任务被取消(通过 task.cancel() 或超时),而协程未传播或处理 CancelledError;在 Python 3.8+ 中它继承自 BaseException 而非 Exception。

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 80% 失败

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