python - 为什么 asyncio 中的异常迟到或根本不出现?

标签 python exception async-await future python-asyncio

有时在使用async/await语法后,我发现程序不再正常工作。但没有任何异常(exception)。 例如:

async def my_func(self):
   async with self.engine() as conn:
      print('step1')  # step1 shows in console
      await conn.exceute("INSERT INTO bla-bla")
      print('step2')  # I can't watch 'step2', and no any exceptions caughted to console

但是如果我使用 try/except 语法可以捕获异常:

async def my_func(self):
   async with self.engine() as conn:
      print('step1')  # step1 shows in console
      try:
          await conn.exceute("INSERT INTO bla-bla")
      except Exception as e:
          print_exc()  # only by this way I can see whats wrong
      print('step2')

所以。我可以立即看到异常而不捕获吗?或者我只能使用步骤并全部调试?

最佳答案

引发异常,堆栈展开。

真正的问题是:你用什么来运行你的协程?

loop.run_until_complete(my_func()) 将按照您的预期处理异常。其他使用场景可能会有所不同。

关于python - 为什么 asyncio 中的异常迟到或根本不出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38875361/

相关文章:

java - 这两种方法中哪一种是处理使用 JDBC 的 DAO 类中关闭 ResultSet、PreparedStatement 和 Connection 的 try-catch 的最佳方法?

javascript - 如何通过 Node.js 中的流传输等待的异步值?

python - Twisted Deferred 在没有 errback 的情况下不显示未处理的异常

javascript - 在 React 组件中使用 Async await 时会出现语法错误

c# - 不同形式的 WCF 服务契约接口(interface)

Python - 如何使用 pdfrw 正确填充 PDF 表单中的多行文本字段?

python - Numpy 数组添加额外列表

python - 如何计算 tensorflow 中张量 A 沿张量 B 指定的权重的轴的加权平均值?

python - 具有多索引的 df.at 与 df.loc

xml - 无效的 XMLDoc - 有多个根元素。 9号线,位置2