Python 中的异常组(ExceptionGroup)
Python 3.11 引入的 ExceptionGroup 是什么?except* 语法如何使用?
回答
小字辈
ExceptionGroup 是一组异常的容器,允许同时抛出和处理多个异常。
# Python 3.11+
try:
raise ExceptionGroup('multiple errors', [
ValueError('invalid value'),
TypeError('wrong type'),
RuntimeError('runtime error')
])
except* ValueError as e:
print(f'Value errors: {e.exceptions}')
except* TypeError as e:
print(f'Type errors: {e.exceptions}')
except* RuntimeError as e:
print(f'Runtime errors: {e.exceptions}')
except* 匹配异常组中所有匹配的异常,而不是像普通 except 只匹配第一个。
使用场景:
asyncio.TaskGroup中多个协程同时失败- 并行任务执行中的多错误收集
- 验证场景,收集所有错误而不是只报告第一个
from asyncio import TaskGroup
async def main():
async with TaskGroup() as tg:
tg.create_task(coro1())
tg.create_task(coro2())
# 如果多个任务失败,抛出 ExceptionGroup