【问题标题】:Why ThreadPoolExecutor ignoring exceptions?为什么 ThreadPoolExecutor 忽略异常?
【发布时间】:2020-11-19 09:37:09
【问题描述】:

我有这样的代码:

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

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

【问题讨论】:

    标签: python concurrency python-multiprocessing python-multithreading threadpoolexecutor


    【解决方案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())
    

    【讨论】:

    猜你喜欢
    • 2016-02-18
    • 2018-09-07
    • 2015-02-18
    • 2011-01-26
    • 1970-01-01
    • 2020-12-01
    • 2015-12-14
    • 2011-03-13
    相关资源
    最近更新 更多