python runtime_error ai_generated true

任务异常从未被获取

Task exception was never retrieved

ID: python/asyncio-task-exception-never-retrieved

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

版本兼容性

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

根因分析

某个 Task 抛出异常,但没有人 await 它或调用 task.exception()。默认事件循环异常处理器在垃圾回收时打印此警告。

English

A Task raised an exception but nobody awaited it or called task.exception(). The default loop exception handler logs this warning at garbage collection.

generic

解决方案

  1. 90% 成功率
    task = asyncio.create_task(worker())
    task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None)
    await task
  2. 93% 成功率
    results = await asyncio.gather(*tasks, return_exceptions=True)
    for r in results:
        if isinstance(r, Exception):
            log.error('task failed', exc_info=r)

无效尝试

常见但无效的做法:

  1. 90% 失败

    It's logged via loop.call_exception_handler, not the warnings module; the underlying failure persists.

  2. 85% 失败

    The exception happens asynchronously inside the task, not at creation time.