Reputation: 29987
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?)
Upvotes: 4
Views: 1598
Reputation: 23753
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()
Upvotes: 6