详解python ThreadPoolExecutor异常捕获

python ThreadPoolExecutor线程池的工作线程中出现异常时,主线程不会捕获异常。

解决方法1:

直接在需要执行的任务方法中添加try:

executor = ThreadPoolExecutor()
executor.submit(test_work, 0)

def test_work(p):
    try:
        1/p
    except Exception as e:
        logger.exception(e)

解决方法2:

添加完成运行时的callback:

executor = ThreadPoolExecutor()
task = executor.submit(test_work, 0)
task.add_done_callback(handle_exception)

handle_exception中又可以通过两种方式捕获异常:

2.1 通过concurrent.futures.Future.exception(timeout=None)

def handle_exception(worker):
    # Method 1: concurrent.futures.Future.exception(timeout=None)
    worker_exception = worker.exception()
    if worker_exception:
        logger.exception(worker_exception)

2.2 通过concurrent.futures.Future.result(Timeout = None)

def handle_exception(worker):
    Method 2: try
    try:
        worker.result()
    except Exception as e:
        logger.exception(e)

原文地址:https://blog.csdn.net/ldahual/article/details/128134915