Rethrow Exception in Python

Rethrow Exception in Python

  1. Throw an Exception in Python
  2. Throw Exception with Custom Message in Python
  3. Rethrow Exception in Python

Python provides us with try-except blocks to handle exceptions in our programs. It also gives us the raise statement to manually throw an exception.

This article will discuss how we can rethrow an exception in a Python program.

Throw an Exception in Python

We can use the raise statement to throw an exception in a program. The syntax for the raise statement is as follows.

raise exception_name

Here, the raise statement takes an exception named exception_name as input and throws the exception that the Python interpreter handles.

For instance, we can raise a ValueError exception in our program using the raise statement.

  1. The following program asks the user to give a number as input using the input() function. The input() function returns the input as a string assigned to the variable number.
  2. After that, the program checks if the input consists of only digits (or not). For this, we use the isdigit() method.

    The isdigit() method, when invoked on a string, checks if all the characters of the string are decimal digits or not. If yes, it returns True; otherwise, it returns False.

number = input("Please Enter a number:")
if number.isdigit():
    number = int(number)
    square = number * number
    print("The square of {} is {}".format(number, square))
else:
    raise ValueError

Output:

Please Enter a number:Aditya
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 7, in <module>
    raise ValueError
ValueError

In the above program, if the input the user gives consists of only decimal digits, the code in the if block is executed. Hence, the input is converted into an integer using the int() function.

Finally, the square of the integer is calculated and printed.

If the input given by the user consists of characters other than decimal digits, the code inside the else statement is executed, and the program throws a ValueError exception.

Here, the ValueError exception is a built-in exception.

Throw Exception with Custom Message in Python

We can also throw a custom exception with a custom message. For this, we will create an exception object using the Exception() constructor.

The Exception() constructor takes a message string as its input argument and returns an exception after execution. We can throw the custom exception using the raise statement, as shown in the following example.

number = input("Please Enter a number:")
if number.isdigit():
    number = int(number)
    square = number * number
    print("The square of {} is {}".format(number, square))
else:
    raise Exception("The input contains characters other than decimal digits.")

Output:

Please Enter a number:Aditya
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 7, in <module>
    raise Exception("The input contains characters other than decimal digits.")
Exception: The input contains characters other than decimal digits.

Here, you can see that the program raises a custom exception with the message The input contains characters other than decimal digits..

Rethrow Exception in Python

Exceptions in Python are handled using try-except blocks. When an exception is thrown in a try block, it is caught in the except block, and proper action is taken.

You can observe this in the example below.

number = input("Please Enter a number:")
try:
    if number.isdigit():
        number = int(number)
        square = number * number
        print("The square of {} is {}".format(number, square))
    else:
        raise Exception("The input contains characters other than decimal digits.")
except Exception:
    print("In the except block. exception handled.")

Output:

Please Enter a number:Aditya
In the except block. exception handled.

Here, the exception is raised in the try block. Then, we catch the exception in the except block, handle it if required, and print an appropriate message.

If you want to rethrow the exception in your Python program, you can use the raise statement in the except block, as shown below.

number = input("Please Enter a number:")
try:
    if number.isdigit():
        number = int(number)
        square = number * number
        print("The square of {} is {}".format(number, square))
    else:
        raise Exception("The input contains characters other than decimal digits.")
except Exception:
    print("In the except block. exception handled. Rethrowing exception.")
    raise

Output:

Please Enter a number:Aditya
In the except block. exception handled. Rethrowing exception.
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 8, in <module>
    raise Exception("The input contains characters other than decimal digits.")
Exception: The input contains characters other than decimal digits.

In this example, we have first caught and handled the exception in the except block. After that, we used the raise statement to rethrow the exception in Python.

Related Article - Python Exception

  • Open File Exception Handling in Python
  • Python Mock Raise Exception
  • Raise Exception in Python
  • Handle NameError Exception in Python
  • Python except Exception as e