Handling a thread's exception in the caller thread in Python
Last Updated :
22 Nov, 2021
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object.
For Exception handling, try-except blocks are used that catch the exceptions raised across the try block and are handled accordingly in the except block
Example:
Python3
# Importing the modules
import threading
import sys
# Custom Thread Class
class MyThread(threading.Thread):
def someFunction(self):
print("Hello World")
def run(self):
self.someFunction()
def join(self):
threading.Thread.join(self)
# Driver function
def main():
t = MyThread()
t.start()
t.join()
# Driver code
if __name__ == '__main__':
main()
Output:
Hello World
For catching and handling a thread's exception in the caller thread we use a variable that stores the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks whether the value of exc is None, if it is then no exception is generated, otherwise, the generated exception that is stored in exc is raised again. This happens in the caller thread and hence can be handled in the caller thread itself.
Example: The example creates a thread t of type MyThread, the run() method for the thread calls the someFunction() method, that raises the MyException, thus whenever the thread is run, it will raise an exception. To catch the exception in the caller thread we maintain a separate variable exc, which is set to the exception raised when the called thread raises an exception. This exc is finally checked in the join() method and if is not None, then join simply raises the same exception. Thus, the caught exception is raised in the caller thread, as join returns in the caller thread (Here The Main Thread) and is thus handled correspondingly.
Python3
# Importing the modules
import threading
import sys
# Custom Exception Class
class MyException(Exception):
pass
# Custom Thread Class
class MyThread(threading.Thread):
# Function that raises the custom exception
def someFunction(self):
name = threading.current_thread().name
raise MyException("An error in thread "+ name)
def run(self):
# Variable that stores the exception, if raised by someFunction
self.exc = None
try:
self.someFunction()
except BaseException as e:
self.exc = 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.exc:
raise self.exc
# Driver function
def main():
# Create a new Thread t
# Here Main is the caller thread
t = MyThread()
t.start()
# Exception handled in Caller thread
try:
t.join()
except Exception as e:
print("Exception Handled in Main, Details of the Exception:", e)
# Driver code
if __name__ == '__main__':
main()
Output:
Exception Handled in Main, Details of the Exception: An error in thread Thread-1
Similar Reads
Test if a function throws an exception in Python The unittest unit testing framework is used to validate that the code performs as designed. To achieve this, unittest supports some important methods in an object-oriented way: test fixturetest casetest suitetest runner A deeper insight for the above terms can be gained from https://www.geeksforgeek
4 min read
How to Print Exception Stack Trace in Python In Python, when an exception occurs, a stack trace provides details about the error, including the function call sequence, exact line and exception type. This helps in debugging and identifying issues quickly.Key Elements of a Stack Trace:Traceback of the most recent callLocation in the programLine
3 min read
Multiple Exception Handling in Python Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they
3 min read
Handling NameError Exception in Python Prerequisites: Python Exception HandlingThere are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are :1. Misspelled built-in functions
2 min read
How to create a new thread in Python Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes. In Python, there
2 min read
Handling OSError exception in Python Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below
2 min read