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.
def childThreadHandleAllHook(args): 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.
def mainHandleAllHook(type, value, traceback): sys.excepthook = mainHandleAllHook |
Example:
# Example Python program that uses a custom exception hook to handle exceptions that are not handled by the child threads # A thread writes one thousand integers to a disk file # A trivial thread function # The custom exception handler def mainExceptionHook(type, value, traceback): # Override sys.excepthook # Override threading.excepthook # Create different child threads childThread2 = threading.Thread(target = threadFunc2) # raise exception from main thread |
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> |