Open In App

Python | Raising an Exception to Another Exception

Last Updated : 12 Jun, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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:
        int('N/A')
    except ValueError as e:
        raise RuntimeError('A parsing error occurred') from e...
  
example()


Output :

Traceback (most recent call last):
  File "", line 3, in example
ValueError: invalid literal for int() with base 10: 'N/A'

This exception is the direct cause of the following exception –

Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in example
RuntimeError: A parsing error occurred

Both exceptions are captured in the traceback. A normal except statement is used to catch such an exception. However, __cause__ attribute of the exception object can be looked to follow the exception chain as explained in the code given below.

Code #2 :




try:
    example()
except RuntimeError as e:
    print("It didn't work:", e)
    if e.__cause__:
        print('Cause:', e.__cause__)


An implicit form of chained exceptions occurs when another exception gets raised inside an except block.

Code #3 :




def example2():
    try:
        int('N/A')
    except ValueError as e:
        print("Couldn't parse:", err)
  
example2()


Traceback (most recent call last):
    File "", line 3, in example2
ValueError: invalid literal for int() with base 10: 'N / A'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
    File "", line 1, in 
    File "", line 5, in example2
NameError: global name 'err' is not defined

In the code below, the NameError exception is raised as the result of a programming error, not in direct response to the parsing error. For this case, the __cause__ attribute of an exception is not set. Instead, a __context__ attribute is set to the prior exception.

Code #4 : To suppress chaining, use raise from None




def example3():
    try:
        int('N / A')
    except ValueError:
        raise RuntimeError('A parsing error occurred') from None...
  
example3()


Output :

Traceback (most recent call last):
    File "", line 1, in 
    File "", line 5, in example3
RuntimeError: A parsing error occurred


Similar Reads

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
Python | Reraise the Last Exception and Issue Warning
Problem - Reraising the exception, that has been caught in the except block. Code #1: Using raise statement all by itself. def example(): try: int('N/A') except ValueError: print("Didn't work") raise example() Output : Didn't work Traceback (most recent call last): File "", line 1, in File "", line 3, in example ValueError: invalid litera
2 min read
Create an Exception Logging Decorator in Python
Prerequisites: Decorators in Python, Logging in Python Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice.
2 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
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.geeksforgeeks.org/unit-testing-python-unittest/ assertRaises()
4 min read
How to print exception stack trace in Python?
Prerequisite: Python Traceback To print stack trace for an exception the suspicious code will be kept in the try block and except block will be employed to handle the exception generated. Here we will be printing the stack trace to handle the exception generated. The printing stack trace for an exception helps in understanding the error and what we
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
How to print the Python Exception/Error Hierarchy?
Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let's try to print the
3 min read
EnvironmentError Exception in Python
EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. exception IOError - It is raised when an I/O operation (when a method of a file object ) fails. e.g "File not found" or "Disk Full".exception OSError - It is raised when
1 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
Article Tags :
Practice Tags :