在 asyncio 中,如何处理协程中抛出的异常?请提供代码示例。

在 asyncio 中,协程中抛出的异常可以通过多种方式处理,具体取决于开发者的需求和使用场景。以下是一些常见的处理方式及其代码示例:

1. 使用 try-except 捕获异常

在协程内部,可以使用普通的 try-except 语句来捕获并处理异常。这是最直接的方法。

import asyncio

async def faulty_coroutine():
    try:
        # 模拟一个可能抛出异常的操作
        await asyncio.sleep(1)
        raise ValueError("Something went wrong!")
    except ValueError as e:
        print(f"Caught an exception: {e}")

async def main():
    await faulty_coroutine()

asyncio.run(main())

2. 使用 asyncio.create_task 和 task.exception()

如果在后台运行多个协程任务,可以通过 asyncio.create_task 创建任务,并在任务完成后检查异常。

import asyncio

async def faulty_coroutine():
    await asyncio.sleep(1)
    raise ValueError("Something went wrong!")

async def main():
    task = asyncio.create_task(faulty_coroutine())
    try:
        await task
    except ValueError as e:
        print(f"Caught an exception: {e}")
    # 或者通过 task.exception() 检查异常
    if task.exception():
        print(f"Task exception: {task.exception()}")

asyncio.run(main())

3. 使用 asyncio.gather 捕获多个协程的异常

asyncio.gather 可以同时运行多个协程,并通过 return_exceptions=True 参数让异常以返回值的形式返回,而不是直接抛出。

import asyncio

async def faulty_coroutine():
    await asyncio.sleep(1)
    raise ValueError("Something went wrong!")

async def another_coroutine():
    await asyncio.sleep(2)
    return "All good!"

async def main():
    results = await asyncio.gather(
        faulty_coroutine(),
        another_coroutine(),
        return_exceptions=True
    )
    for result in results:
        if isinstance(result, Exception):
            print(f"Caught an exception: {result}")
        else:
            print(f"Result: {result}")

asyncio.run(main())

4. 使用 asyncio.wait 和 done 集合检查异常

asyncio.wait 可以等待多个协程完成,并通过 done 和 pending 集合检查异常。

import asyncio

async def faulty_coroutine():
    await asyncio.sleep(1)
    raise ValueError("Something went wrong!")

async def main():
    task = asyncio.create_task(faulty_coroutine())
    done, pending = await asyncio.wait({task})
    for t in done:
        if t.exception():
            print(f"Caught an exception: {t.exception()}")

asyncio.run(main())

5. 为协程添加异常回调

可以为 task 添加回调函数,在异常发生时进行处理。

import asyncio

async def faulty_coroutine():
    await asyncio.sleep(1)
    raise ValueError("Something went wrong!")

def handle_exception(task):
    if task.exception():
        print(f"Caught an exception in callback: {task.exception()}")

async def main():
    task = asyncio.create_task(faulty_coroutine())
    task.add_done_callback(handle_exception)
    try:
        await task
    except:
        pass  # 异常已经在回调中处理

asyncio.run(main())

通过这些方法,可以灵活处理协程中抛出的异常。选择哪种方式取决于具体的需求和代码结构。