为什么 ThreadPoolExecutor 忽略异常?
Why ThreadPoolExecutor ignoring exceptions?
我有这样的代码:
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())
我有这样的代码:
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())