有时在使用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/