首页 > 解决方案 > 为什么会立即从 asyncio 任务中引发此异常?

问题描述

我从文档中的理解是,asyncio.Tasks 作为 asyncio.Future 的子类,将存储其中引发的异常,并且可以在我闲暇时检索它们。

但是,在此示例代码中,会立即引发异常:

import asyncio

async def bad_task():
    raise Exception()

async def test():
    loop = asyncio.get_event_loop()
    task = loop.create_task(bad_task())
    await task

    # I would expect to get here
    exp = task.exception()
    # but we never do because the function exits on line 3

loop = asyncio.get_event_loop()
loop.run_until_complete(test())
loop.close()

示例输出(Python 3.6.5):

python3 ./test.py
Traceback (most recent call last):
  File "./test.py", line 15, in <module>
    loop.run_until_complete(test())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
    return future.result()
  File "./test.py", line 9, in test
    await task
  File "./test.py", line 4, in bad_task
    raise Exception()
Exception

这是在异步代码中创建和调用任务的怪癖吗?

标签: python-3.xpython-asyncio

解决方案


await将引发任务抛出的任何异常,因为它旨在使异步代码看起来几乎与同步代码完全相同。如果你想抓住它们,你可以使用普通try...except子句。


推荐阅读