Open In App

Handling a thread’s exception in the caller thread in Python

Last Updated : 22 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

Caller ID Lookup using Python
Prerequisite : Beautiful soupRequests module In this article, we are going to see how we get Caller Id information using numverify API. Numverify offers a powerful tool to deliver phone number validation and information lookup in portable JSON format by Just making a request using a simple URL. For the following program to work you must have an API
2 min read
Python | Raising an Exception to Another Exception
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: in
2 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 can be grouped together in a tuple as shown in th
3 min read
Handling TypeError Exception in Python
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeError being raised are: 1. Unsupported Operation Betwe
3 min read
Handling NameError Exception in Python
Prerequisites: Python Exception Handling There 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: In the below example code, the print statement
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 is an example of OSError: Python Code # Importing
2 min read
Handling EOFError Exception in Python
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box. We can overcome this issue by using try and except
1 min read
Exception Handling Of Python Requests Module
Python request module is a simple and elegant Python HTTP library. It provides methods for accessing Web resources via HTTP. In the following article, we will use the HTTP GET method in the Request module. This method requests data from the server and the Exception handling comes in handy when the response is not successful. Here, we will go throug
4 min read
Python Exception Handling
We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4). In this article, we will discuss how to handle exceptions in Python using try, except, and finally statements with the help of proper examples. Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a program due to which t
9 min read
Output of Python programs | Set 10 (Exception Handling)
Pre-requisite: Exception Handling in Python Note: All the programs run on python version 3 and above. 1) What is the output of the following program? data = 50 try: data = data/0 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') else: print('Division successful ', end = '') try: data = data/5 except: print('Inside except block ', end
3 min read
Article Tags :
Practice Tags :