I have a set of functions I would like to execute in threads. Some of these functions may raise a specific exception I would like to catch, separately for each thread.
I tried something along the lines of
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")
I expected to see caught MyException twice, one for each thread. But there is only one.
Is it possible to catch exceptions in threads independently of each other? (in other words: when a thread raises an exception, manage it in the code that called the thread?)
For Python 3.8+ you can define a handler for uncaught exceptions.
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()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With