Handling a Thread’s Exception
The threading library in Python may be used to achieve multithreading. The caller thread constructs a thread object and calls the start method to invoke a thread. When the join method is invoked, it starts its execution and calls the class object's run method.
Exceptions are handled using try-except blocks, which capture exceptions raised throughout the try block and handle them appropriately in the except block.
Example:
import threading
import sys
# Custom Thread Class
class SampleThread(threading.Thread):
def sampleFunction(self):
print("Hello Ninjas!!")
def run(self):
self.sampleFunction()
def join(self):
threading.Thread.join(self)
def main():
t = SampleThread()
t.start()
t.join()
if __name__ == '__main__':
main()

You can also try this code with Online Python Compiler
Run Code
Output:
Hello Ninjas!!

You can also try this code with Online Python Compiler
Run Code
We use a variable named ex to store the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks if the value of ex is None; if it is, no exception is issued; otherwise, the generated exception that is kept in ex is raised again. Because this occurs in the caller thread, it may also be addressed there.
Example:
import threading
import sys
# Custom Exception Class
class SampleException(Exception):
pass
# Custom Thread Class
class SampleThread(threading.Thread):
# Function raising the custom exception
def sampleFunction(self):
name = threading.current_thread().name
raise SampleException("An error occurred in thread "+ name)
def run(self):
# Variable storing the exception, if raised by sampleFunction
self.ex = None
try:
self.sampleFunction()
except BaseException as e:
self.ex = e
def join(self):
threading.Thread.join(self)
# Since join() returns in caller thread
# we re-raise the caught exception
# if any was caught
if self.ex:
raise self.ex
def main():
# Create a new Thread t
# Here Main is the caller thread
t = SampleThread()
t.start()
# Exception handled in the Caller thread
try:
t.join()
except Exception as e:
print("The exception has been Handled in the Main, Details of the Exception are:\n",e)
if __name__ == '__main__':
main()

You can also try this code with Online Python Compiler
Run Code
Output:
The exception has been Handled in the Main, Details of the Exception are:
An error occurred in thread Thread-1

You can also try this code with Online Python Compiler
Run Code
The example generates a thread t of type SampleThread. The thread's run() function calls the SampleFunction() method, which raises the SampleException; thus, the thread will produce an exception anytime it is run. To catch the exception in the caller thread, we keep a separate variable ex, which is set to the exception raised when the called thread raises an exception. Finally, in the join() method, this ex is tested, and if it is not None, join just throws the same exception. As a result, the caught exception is raised on the caller thread (Here The Main Thread) and is handled appropriately.
You can try it on online python compiler.
Also Read, leap year program in python
FAQs
How do you handle an unhandled exception in the thread?
The exception does not need to be sent from one thread to another. If you need to handle an exception, do it in the thread that caused it.
How do you handle a specific exception in Python?
Exceptions in Python may be handled with the try statement. The try clause contains the critical operation that might cause an exception. The except clause contains the code that handles exceptions. As a result, after we've caught the exception, we may pick which actions to perform.
What happens if the thread throws exception Python?
When a child thread throws an exception, it is forwarded to the parent thread through a Queue and thrown in the parent thread once more.
Conclusion
In this article, we have extensively discussed threads and how to handle them in python. We also learned to handle the thread exception in python with the help of examples.
For more such articles refer to A Complete Preparation Guide for Coding Interviews, Attempt Unlimited Coding Mock Test Series Online (FREE) - Coding Ninjas Studio, Interview Experiences of top tech companies for practice, Coding Interview Questions and answers for practice | Python, Java & C++, Top 100 SQL Problems, Curated articles and videos for your interview preparation, Interview Preparation Resources for Software Development Engineer | Coding Ninjas Studio.
Do upvote our blog to help other ninjas grow. Happy Coding!