Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exceptions from multiple threads?

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?)

like image 609
WoJ Avatar asked Oct 30 '25 10:10

WoJ


1 Answers

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()
like image 119
wwii Avatar answered Nov 01 '25 01:11

wwii