在Python中,協程(coroutine)是一種特殊的函數,可以在執行過程中暫停和恢復。處理協程中的異常與處理普通函數的異常類似,但有一些不同之處。當協程中發生異常時,它會被捕獲并存儲在協程對象的_exception屬性中。要處理協程中的異常,可以使用asyncio.gather()函數,它會收集多個協程的結果,并將它們迭代器返回。如果在協程中發生異常,asyncio.gather()會立即停止執行其他協程,并將異常傳遞給return_exceptions參數指定的回調函數。
下面是一個處理協程異常的示例:
import asyncio
async def raise_exception():
raise ValueError("An error occurred in the coroutine")
async def handle_exception(task):
try:
await task
except Exception as e:
print(f"Caught exception: {e}")
async def main():
task1 = asyncio.create_task(raise_exception())
task2 = asyncio.create_task(asyncio.sleep(1)) # This will not raise an exception
results = await asyncio.gather(task1, task2, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
handle_exception(result)
else:
print(f"Result: {result}")
asyncio.run(main())
在這個示例中,我們定義了一個名為raise_exception的協程,它會引發一個ValueError異常。我們還定義了一個名為handle_exception的協程,用于處理異常。在main協程中,我們使用asyncio.gather()函數執行raise_exception和asyncio.sleep(1)協程。我們將return_exceptions參數設置為True,以便在發生異常時將它們傳遞給handle_exception協程。最后,我們遍歷results列表,并根據結果類型調用相應的處理函數。