Threads are independent tasks that run concurrently and unhandled exceptions in threads can lead to unexpected behavior and a crash of the application.
The default behaviour of exceptions in a thread is different when compared to the exceptions in the main thread.
By default, when an exception occurs in a thread, it doesn’t propagate to the main thread. Instead, the exception is raised within the thread context, and if it’s not handled properly, the thread will terminate without any intimation.
Catch exceptions within the threads
The simplest way to handle exceptions in threads is to catch them within the thread’s execution function. We can keep the code inside a try-except
block and handle the exception accordingly. If any exception comes in the try block, the except block will be executed and the exception can be handled here.
Following is the example
import threading
def thread_function():
try:
# Your thread code here
pass
except Exception as e:
print("Exception in thread:", e)
thread = threading.Thread(target=thread_function)
thread.start()
Propate the exceptions to the main thread
Some times we may need to propagate the exceptions to main thread such that the main thread will take descision based on the descision. To propagate exceptions from threads to the main thread, we can use the threading.excepthook
function. This function allows us to set a global exception handler for all threads.
import threading
def exception_handler(args):
print("Exception in thread:", args)
threading.excepthook = exception_handler
def thread_function():
# Your thread code here
pass
thread = threading.Thread(target=thread_function)
thread.start()
In the above example, any unhandled exception raised in the thread will be caught by the exception_handler
function and printed.