ExceptionGroup仅在asyncio.gather(return_exceptions=False)或TaskGroup中多个协程各自抛出不同异常时触发;需显式except ExceptionGroup或except*按类型分流处理,且不被except Exception捕获。

ExceptionGroup在asyncio.gather中实际触发的条件
Python 3.11 的 ExceptionGroup 不会自动出现在普通 try/except 中——它只在并发任务聚合失败时由 asyncio.gather(..., return_exceptions=False)(默认行为)抛出。如果你用 return_exceptions=True,错误会被包裹成正常返回值,根本不会触发 ExceptionGroup。
常见误判是以为单个 await 或同步代码能直接 raise ExceptionGroup,其实不能。它本质是并发原语的“聚合异常容器”,不是通用异常类型。
- 必须用
asyncio.gather()或asyncio.TaskGroup启动多个协程 - 其中至少两个协程各自抛出不同异常(比如一个
ValueError,一个TimeoutError) - 且未设置
return_exceptions=True
捕获ExceptionGroup的正确except写法
不能只写 except Exception: ——虽然 ExceptionGroup 继承自 BaseException,但它**不继承自 Exception**(和 KeyboardInterrupt、SystemExit 同级)。所以常规 except Exception 会漏掉它。
必须显式捕获:except ExceptionGroup:,或更稳妥地写成 except (ExceptionGroup, Exception):(兼顾子异常和传统异常)。
立即学习“Python免费学习笔记(深入)”;
try:
await asyncio.gather(coro_a(), coro_b())
except ExceptionGroup as eg:
print(f"并发任务组失败,共 {len(eg.exceptions)} 个异常")
for i, exc in enumerate(eg.exceptions):
print(f"[{i}] {type(exc).__name__}: {exc}")用except*语法分别处理不同类型的子异常
except* 是 Python 3.11 专为 ExceptionGroup 设计的语法,能按子异常类型精准分流,比手动遍历 eg.exceptions 更安全、更符合语义。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
它不是“捕获一部分异常就结束”,而是对 ExceptionGroup 中**所有匹配类型的子异常**分别执行对应块,未被匹配的子异常仍保留在原组中;如果最后还有未处理的子异常,会重新抛出精简后的 ExceptionGroup。
-
except* ValueError:→ 处理所有ValueError子项 -
except* TimeoutError:→ 处理所有TimeoutError子项 -
except* Exception:→ 作为兜底,捕获其余所有(但注意:不包括BaseException子类如SystemExit)
try:
await asyncio.gather(fetch_user(), fetch_config(), fetch_cache())
except* ValueError as eg:
log_warning(f"用户或配置数据格式错误:{eg}")
except* ConnectionError as eg:
retry_network_tasks(eg.exceptions)
except* Exception as eg:
report_unexpected_failures(eg.exceptions)TaskGroup里ExceptionGroup的传播与抑制
用 async with asyncio.TaskGroup() 时,只要任一子任务失败,TaskGroup 就立即 cancel 其他运行中任务,并把所有已发生的异常(包括被 cancel 引发的 CancelledError)打包进一个 ExceptionGroup 抛出。这点和 gather 不同——gather 等所有任务完成才聚合异常。
想抑制某个特定异常(比如允许 CancelledError 静默失败),不能靠 except* 捕获后忽略,而要用 eg.subgroup() 提取并丢弃:
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(download_file("a.zip"))
tg.create_task(download_file("b.zip"))
except ExceptionGroup as eg:
# 只保留非 CancelledError 的异常
real_errors = eg.subgroup(lambda e: not isinstance(e, asyncio.CancelledError))
if real_errors is not None:
raise real_errors注意:subgroup 返回 None 表示没找到匹配项,此时不应再 raise;另外 subgroup 不修改原 ExceptionGroup,是纯函数式操作。
真正容易被忽略的是:TaskGroup 的 cancel 行为不可逆,且 CancelledError 默认不被 except* 的 Exception 分支捕获(因为它是 BaseException 子类),必须显式写 except* CancelledError 或用 subgroup 过滤。

















