python runtime_error ai_generated true

Task exception was never retrieved

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-02-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8+ active
3.9+ active
3.10+ active
3.11+ active
3.12+ active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 85% fail

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