Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What Is a Thread?
3.
Handling a Thread’s Exception 
4.
FAQs
4.1.
How do you handle an unhandled exception in the thread?
4.2.
How do you handle a specific exception in Python?
4.3.
What happens if the thread throws exception Python?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

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

Author Sanjana Yadav
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Python threading allows you to execute multiple portions of your program concurrently, simplifying program design. If you have some Python knowledge and wish to speed up your application using threads, this article is for you!

Also read, Floor Division in Python and Convert String to List Python.

What Is a Thread?

In computing, a process is a running instance of a computer program. Every process includes three essential components:

  • An executable program.
  • The program's requirement for the associated data (variables, workspace, buffers, etc.)
  • The program's execution context (State of the process)

A thread is a process object that may be scheduled for execution. It is also the smallest unit of processing that may be performed in an operating system (Operating System).

A thread, in simple terms, is a sequence of such instructions inside a program that may be run independently of other code. For simplicity, consider a thread to be a subset of a process!

All of this information is included in a Thread Control Block (TCB) in a thread:

Thread Identifier: Each new thread is granted a unique id (TID).

Stack pointer: A pointer to the thread's stack in the process. The stack stores the thread's local variables.

Program counter: A program counter is a register that holds the address of the instruction that is presently being executed by the thread.

Thread State: The thread state might be running, ready, waiting, starting, or completed.

Thread's register set: the registers that have been assigned to the thread for calculations.

Parent process Pointer: A pointer to the process control block (PCB) on which the thread is running.

Recommended Topic, Divmod in PythonFibonacci Series in Python

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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()

Output:

Hello Ninjas!!

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()

Output:

The exception has been Handled in the Main, Details of the Exception are:
 An error occurred in thread Thread-1

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 StudioInterview Experiences of top tech companies for practiceCoding Interview Questions and answers for practice | Python, Java & C++Top 100 SQL ProblemsCurated articles and videos for your interview preparationInterview Preparation Resources for Software Development Engineer | Coding Ninjas Studio.
Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Multiple exception handling in python
Next article
Handling NameError Exception in Python
Live masterclass