如何捕获多个线程的异常?

WoJ*_*WoJ 4 python multithreading exception python-multithreading python-3.x

我有一组想要在线程中执行的函数。其中一些函数可能会引发我想要捕获的特定异常,分别为每个线程。

我尝试了一些类似的事情

import threading

class MyException(Exception):
    pass

def fun():
    raise MyException

myfuns = [threading.Thread(target=fun), threading.Thread(target=fun)]
for myfun in myfuns:
    try:
        myfun.start()
    except MyException:
        print("caught MyException")
Run Code Online (Sandbox Code Playgroud)

我预计会看到caught MyException两次,每个线程一次。但只有一个。

是否可以独立地捕获线程中的异常?(换句话说:当线程引发异常时,在调用该线程的代码中对其进行管理?)

wwi*_*wii 6

对于 Python 3.8+,您可以为未捕获的异常定义处理程序。

import threading

def f(args):
    print(f'caught {args.exc_type} with value {args.exc_value} in thread {args.thread}\n')
    
threading.excepthook = f

class MyException(Exception):
    pass

def fun():
    raise MyException

myfuns = [threading.Thread(target=fun), threading.Thread(target=fun)]
for myfun in myfuns:
    myfun.start()
for myfun in myfuns:
    myfun.join()
Run Code Online (Sandbox Code Playgroud)