The excepthook() function of Python threading module

Once overridden the excepthook() function of Python threading module will handle any unhandled exceptions from child threads.

Threading Module Updated 20 Jul 2024 2 min read

Function Name

excepthook()

Function Signature

excepthook(args, /)

Returns

none

Overview

  • The threading.excepthook is an exception handler function with an args parameter.
  • Exceptions that are not handled by the child threads are handled by the threading.excepthook handler.
  • In order to handle such unhandled exceptions threading.excepthook has to be overridden with the custom exception handler with an args parameter.
python
def childThreadHandleAllHook(args):

                print(“====Common handler for all child threads===”):

                print(args.exc_type)

                print(exc_value)

                print(exc_traceback)

                print(thread)

                print(“====”)

threading.excepthook = childThreadHandleAllHook
  • The threading.excepthook will not handle any exceptions that are not handled by the main thread. To handle the unhandled exceptions of the main thread sys.excepthook has to be overridden.
python
def mainHandleAllHook(type, value, traceback):

                print(“====Catch all for main thread===”)

                print(type)

                print(value)

                print(traceback)

sys.excepthook = mainHandleAllHook

Example

python
# Example Python program that uses a custom exception hook to handle exceptions that are not handled by the child threads

            import threading

            import sys

# A thread writes one thousand integers to a disk file

            # and raises OSError for any failure

            # during the writes, which also raises an Exception

            # as it exits

            def threadFunc1():

                print("Child thread - enter")

                try:

                    diskFile = open("1000ints.txt", "w")

                    for i in range(0, 1000):

                        diskFile.write("{}".format(i))

                        if(i < 1000):

                            diskFile.write(",")

                except OSError as ose:

                    print("Error opening/writing to file")

                print("Child thread - before exit")

                raise Exception("Another odd exception")

# A trivial thread function

            def threadFunc2():

                raise Exception("From threadFunc2")

# The custom exception handler

            def threadExceptionHook(args):

                print("No handlers? I am here...from threadExceptionHook...")

                print("=====Begin child thread exception info:=====")

                print(args.exc_type)

                print(args.exc_value)

                print(args.exc_traceback)

                print(args.thread)

                print("=====End child thread exception info=====")

def mainExceptionHook(type, value, traceback):

                print("From mainExceptionHook:")

                print(type)

                print(value)

                print(traceback)

# Override sys.excepthook

            sys.excepthook          = mainExceptionHook

# Override threading.excepthook

            threading.excepthook = threadExceptionHook

# Create different child threads

            childThread1 = threading.Thread(target = threadFunc1)

            childThread1.start()

            childThread1.join()

childThread2 = threading.Thread(target = threadFunc2)

            childThread2.start()

            childThread2.join()

# raise exception from main thread

            raise Exception("From main")

Output

Output
Child thread - enter

Child thread - before exit

No handlers? I am here...from threadExceptionHook...

=====Begin child thread exception info:=====

<class 'Exception'>

Another odd exception

<traceback object at 0x10091ec80>

<Thread(Thread-1 (threadFunc1), started 6180892672)>

=====End child thread exception info=====

No handlers? I am here...from threadExceptionHook...

=====Begin child thread exception info:=====

<class 'Exception'>

From threadFunc2

<traceback object at 0x10091edc0>

<Thread(Thread-2 (threadFunc2), started 6180892672)>

=====End child thread exception info=====

From mainExceptionHook:

<class 'Exception'>

From main

<traceback object at 0x1008bf100>