Handle Python Exception in Threads



Python allows you to run multiple tasks at the same time using threads. However, handling exceptions in threads can be tricky because exceptions that happen inside a thread don't get passed to the main thread by default.

To deal with this, you can catch errors inside the thread's function or create a custom thread class to handle them. This helps you to find issues in threads and handle them properly in the main program.

Exception Handling in Threads

When an exception occurs inside a thread, it only affects that thread, and unless explicitly handled, it will be ignored silently. To properly handle these exceptions, we need to catch them inside the thread function.

Example

In the following example, we start a thread that raises an exception. If we don't catch it inside the thread, the main program does not know about it -

import threading

def faulty_thread():
   print("Thread started")
   raise ValueError("Something went wrong inside the thread")

t = threading.Thread(target=faulty_thread)
t.start()
t.join()
print("Main program continues...")

We can see in the output below that the thread crashes with a ValueError, but the main program continues execution -

Thread started
Exception in thread Thread-1 (faulty_thread):
Traceback (most recent call last):
  ...
ValueError: Something went wrong inside the thread
Main program continues...

Handling Exception Inside the Thread

To catch exceptions, wrap the code inside the thread's target function using a try-except block. This way, any error that occurs within the thread can be handled without crashing the program.

Example

In this example, the exception is caught and handled within the thread, so the thread does not crash unexpectedly -

import threading

def safe_thread():
   try:
      print("Thread started")
      raise ValueError("Error inside thread")
   except Exception as e:
      print("Caught exception in thread:", e)

t = threading.Thread(target=safe_thread)
t.start()
t.join()
print("Main program continues...")

Following is the output obtained -

Thread started
Caught exception in thread: Error inside thread
Main program continues...

Using Thread Subclass to Capture Exceptions

You can also create a custom thread class that captures exceptions and stores them in an attribute. This allows the main program to check for errors after the thread has finished running.

Example

In this example, we subclass Thread to save any exception that occurs and check it after the thread has finished -

import threading

class SafeThread(threading.Thread):
   def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
      self.exception = None

   def run(self):
      try:
         if self._target:
            self._target(*self._args, **self._kwargs)
      except Exception as e:
         self.exception = e

def task():
   raise RuntimeError("Thread failure")

t = SafeThread(target=task)
t.start()
t.join()

if t.exception:
   print("Exception caught from thread:", t.exception)

We get the output as shown below -

Exception caught from thread: Thread failure
Updated on: 2025-06-02T15:35:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements