在python 3.11中,利用 exceptiongroup 捕获异步多重异常的核心做法是:使用 try...except* ... except... 语法结构。当多个协程并发执行(如通过 asyncio.gather)且部分失败时,它们会被自动包装进一个 exceptiongroup 对象中抛出。开发者可以通过 except* 块来匹配并处理组内的特定异常类型,而剩余的未处理异常则继续向上传播或进入下一个 except* 分支。

如何区分同步与异步代码中的异常传播差异?
在同步代码中,如果循环内多个函数调用抛出异常,只有第一个异常会被抛出,后续异常被静默丢弃;而在异步代码中,若使用 asyncio.gather(..., return_exceptions=False),所有协程的异常都会被收集并打包成一个 ExceptionGroup 一次性抛出。这种差异使得异步环境更适合批量任务处理,但也要求开发者必须使用新的 except* 语法来解构这些异常。

import asyncio
async def task_a():
raise ValueError("Task A failed")
async def task_b():
raise TypeError("Task B failed")
async def main():
try:
# gather 会等待所有协程完成,并将异常打包
await asyncio.gather(task_a(), task_b())
except* ValueError as eg:
print(f"Caught ValueErrors: {eg.exceptions}")
except* TypeError as eg:
print(f"Caught TypeErrors: {eg.exceptions}")
except BaseException as eg:
print(f"Remaining exceptions: {eg.exceptions}")
asyncio.run(main())
如何在嵌套结构中筛选特定类型的异常?
当 ExceptionGroup 包含嵌套的子组时,可以使用 split() 方法将异常按类型分离。该方法返回一个元组,其中第一个元素是匹配到的异常列表,第二个元素是剩余未匹配的异常(可能是另一个 ExceptionGroup 或单个异常)。这种方式允许开发者逐层剥离异常,只处理关心的部分,而不必关心其他无关的错误。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import asyncio
from exceptiongroup import ExceptionGroup
async def nested_task():
async def inner_fail():
raise RuntimeError("Inner failure")
try:
await inner_fail()
except RuntimeError as e:
# 模拟嵌套结构
raise ExceptionGroup("Outer group", [e]) from None
async def main():
try:
await nested_task()
except* RuntimeError as (matched, remaining):
print(f"Matched RuntimeErrors: {matched}")
if remaining:
print(f"Remaining: {remaining}")
asyncio.run(main())
基于gather返回结果的具体问题:如何处理混合成功与失败的协程?
当使用 asyncio.gather 时,如果希望即使有异常也获取部分结果,可以设置 return_exceptions=True。此时,失败的协程不会抛出 ExceptionGroup,而是将异常实例作为普通返回值放入结果列表中。开发者需要遍历结果列表,检查每个元素是否为异常实例,从而区分成功和失败的任务。这种方法适用于需要“尽力而为”策略的场景,即不因为个别任务失败而中断整个流程。
,
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










