I am trying to handle uncaught exceptions that occur when I run a thread. The python documentation at docs.python.org states that "threading.excepthook()
can be overridden to control how uncaught exceptions raised by Thread.run()
are handled." However, I can't seem to do it properly. It doesn't appear that my excepthook
function is ever excecuted. What is the correct way to do this?
import threading
import time
class MyThread(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def excepthook(self, *args, **kwargs):
print("In excepthook")
def error_soon(timeout):
time.sleep(timeout)
raise Exception("Time is up!")
my_thread = MyThread(target=error_soon, args=(3,))
my_thread.start()
time.sleep(7)
Given the Python documentation for Thread. run() : You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
For catching and handling a thread's exception in the caller thread we use a variable that stores the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks whether the value of exc is None, if it is then no exception is generated, otherwise, the generated ...
Using a hidden function _stop() : In order to kill a thread, we use hidden function _stop() this function is not documented but might disappear in the next version of python.
threading.excepthook
is a function that belongs to the threading
module, not a method of the threading.Thread
class, so you should override threading.excepthook
instead with your own function:
import threading
import time
def excepthook(args):
print("In excepthook")
threading.excepthook = excepthook
class MyThread(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def error_soon(timeout):
time.sleep(timeout)
raise Exception("Time is up!")
my_thread = MyThread(target=error_soon, args=(3,))
my_thread.start()
time.sleep(7)
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