ThreadPoolExecutor/ProcessPoolExecutor不抛出异常的问题


from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

"""
在使用线程池/进程池之后,如果任务函数中出现异常,如果不调用result异常并不会抛出,导致一种没有报错的假象
"""

def func():
    lst = [1, 2]
    # 写一个bug,测试是否或报错
    print(lst[3])


def callbak(f):
    exception = f.exception()
    if exception:
        # 如果exception获取到了值,说明有异常.exception就是异常类
        print(exception)


if __name__ == '__main__':
    pool = ThreadPoolExecutor(1)
    # 用这种方法不会异常,ThreadPoolExecutor/ProcessPoolExecutor会将异常封装到futures对象中,需要调用.exception()方法获取异常
    pool.submit(func).add_done_callback(callbak)

    pool.shutdown()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM