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

Why exceptions in asnycio are late or do not appear at all?

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

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')

所以。我可以在不捕获的情况下立即看到异常吗?还是我只能用steps全部debug?

引发异常,展开堆栈。

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

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