You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用task.exception()后仍遇“Task exception was never retrieved”错误排查

问题原因及修复方案

你遇到的Task exception was never retrieved警告,核心原因是被取消的任务抛出的CancelledError未被显式获取,以下是具体分析和修复方案:

具体问题点

当你调用task.cancel()后,任务会抛出asyncio.CancelledError。你的代码中仅处理了非CancelledError的异常,对于抛出CancelledError的任务,没有调用task.exception()或task.result()来获取这个异常。asyncio要求所有任务的异常(包括取消错误)都必须被显式获取,否则会触发该警告。

修复代码

修改取消任务后的处理逻辑,确保所有完成任务的异常都被获取:

if count_exc > max_exc:
    print("Too many exceptions happened, cancelling pending tasks")
    for task in pending_tasks:
        task.cancel()
    while pending_tasks:
        done, pending_tasks = await asyncio.wait(pending_tasks, return_when=asyncio.ALL_COMPLETED)
        for task in done:
            exc = task.exception()
            if exc is not None:
                if isinstance(exc, asyncio.CancelledError):
                    # 取消错误无需打印,只需确认获取即可
                    continue
                print(f"\n{task.get_name()} raised Exception: <{type(exc)}> {exc}")
    raise RuntimeError("Too many exceptions")

补充说明

  • 只要调用task.exception()(无论返回None还是具体异常),asyncio就会认为该任务的异常已被处理,不会触发警告。
  • 被取消的任务必须获取其CancelledError,即使你不需要处理它,否则asyncio会在任务被垃圾回收时抛出警告。

内容的提问来源于stack exchange,提问作者ClaireM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 11:57:19