What is the proper way to override threading.excepthook in Python?

Viewed 4113

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)
1 Answers

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