except* 是捕获 ExceptionGroup 的唯一正确方式,它能分流匹配子异常,而普通 except 只匹配外层组对象本身。

用 except* 捕获 ExceptionGroup 是唯一正确方式
Python 3.11 引入 ExceptionGroup 后,传统 except 无法解包多个异常——它只匹配最外层的 ExceptionGroup 实例本身,不会自动遍历子异常。必须用新语法 except* 才能真正“捕获并分流”其中的各类异常。
常见错误是写成这样:
try:
raise ExceptionGroup("eg", [ValueError("bad"), TypeError("nope")])
except ValueError: # ❌ 不会进入这里
print("got value error")
except TypeError: # ❌ 也不会进入这里
print("got type error")实际只会触发 Uncaught ExceptionGroup,因为 ExceptionGroup 不是 ValueError 的子类(它是平行结构)。
-
except*是专为ExceptionGroup设计的语法,支持同时匹配多个子异常 - 一个
except*块可匹配零个、一个或多个子异常,不中断其余未匹配的异常传播 - 可以写多个
except*块,按顺序尝试匹配剩余未处理的子异常
except* 的匹配行为和嵌套传播规则
except* 不是“全有或全无”,而是“尽力匹配”:对 ExceptionGroup 中每个子异常单独尝试匹配,匹配成功的被该块处理,失败的继续留在组内,供后续 except* 块处理,或最终冒泡为未捕获异常。
立即学习“Python免费学习笔记(深入)”;
示例:
try:
raise ExceptionGroup("ops", [
ValueError("bad input"),
OSError(2, "No such file"),
RuntimeError("uh oh")
])
except* ValueError as eg:
print(f"ValueErrors: {len(eg.exceptions)}")
except* OSError as eg:
print(f"OSError: {eg.exceptions[0]}")
except* Exception as eg:
print(f"others: {eg.exceptions}")输出:
ValueErrors: 1
OSError: [Errno 2] No such file
others: [RuntimeError('uh oh')]- 每个
except*接收的是一个新ExceptionGroup,只含本次匹配到的子异常(eg.exceptions是列表) - 未被任何
except*匹配的子异常,会保留在原组中继续向上抛出 - 如果所有子异常都未被匹配,整个
ExceptionGroup仍会冒泡,不会静默丢弃
与 except 混用时的优先级和陷阱
except 和 except* 可共存,但顺序和意图容易混淆。关键点:普通 except 先于 except* 运行,且它只看到最外层的 ExceptionGroup 对象本身。
例如:
try:
raise ExceptionGroup("eg", [KeyError("x"), ZeroDivisionError()])
except ExceptionGroup: # ✅ 能捕获,但你拿到的是整个组,不是子异常
print("caught the group itself")
except* KeyError: # ❌ 永远不会执行,因为上面已捕获
pass反过来说,如果想先处理特定子异常,再兜底处理整个组,必须把 except* 放在前面:
- 把
except*块写在except块之前,否则后者会提前截断 - 避免用
except BaseException:或except Exception:在except*之前——它会吞掉整个组 - 若真需要兜底捕获未被
except*处理的剩余异常,可用except* Exception:,它只匹配剩下的子异常,不干扰已有逻辑
实际协程/TaskGroup 场景下的典型用法
asyncio.TaskGroup(Python 3.11+)在多个任务出错时会自动抛出 ExceptionGroup,这是最常遇到该异常的地方。此时不能靠单个 except 安全处理。
正确写法:
import asyncioasync def main(): try: async with asyncio.TaskGroup() as tg: tg.create_task(asyncio.sleep(1)) tg.create_task(crash_soon()) except ValueError as eg: for e in eg.exceptions: print("ValueError from task:", e) except RuntimeError as eg: print("RuntimeError group size:", len(eg.exceptions))
async def crash_soon(): await asyncio.sleep(0.1) raise ValueError("oops")
注意:
- 不要试图在
TaskGroup外层用except ValueError:——它不会命中 - 若任务中混发多种异常(如部分超时、部分解析失败),
except*是唯一能分类响应的方式 -
ExceptionGroup的message(如"unhandled errors")只是提示,真正信息在.exceptions列表里
最容易被忽略的是:即使只预期一种异常类型,也得用 except*,而不是退化回 except 加手动遍历 __cause__ 或 args——那既不可靠也不符合语义。










