为什么ThreadPoolExecutor忽略异常



我有一个这样的代码:

from concurrent.futures.thread import ThreadPoolExecutor
from time import sleep

def foo(message, time):
sleep(time)
print('Before exception in ' + message)
raise Exception('OOOPS! EXCEPTION IN ' + message)

if __name__ == '__main__':
executor = ThreadPoolExecutor(max_workers=2)
future1 = executor.submit(foo, 'first', 1)
future2 = executor.submit(foo, 'second', 3)
print(future1.result())
print(future2.result())

当我运行这个程序时,我会得到以下结果:

Before exception in first
Traceback (most recent call last):
...
File "...", line 8, in foo
raise Exception('OOOPS! EXCEPTION IN ' + message)
Exception: OOOPS! EXCEPTION IN first
Before exception in second
Process finished with exit code 1

为什么第二个异常被忽略?我想捕获并处理每个线程上的异常

因为异常result()引发并阻止正常的脚本流。要查看第二个异常,您需要捕获第一个异常:

executor = ThreadPoolExecutor(max_workers=2)
future1 = executor.submit(foo, 'first', 1)
future2 = executor.submit(foo, 'second', 3)
try:
print(future1.result())
except:
pass
print(future2.result())

相关内容

  • 没有找到相关文章

最新更新