How to Raise Exception in Python

In this tutorial, we will learn how to raise an exception in Python with the help of examples.

When an error occurs in a program, Python automatically raises exceptions during the execution of the program. However, Python also allows us to define an exception in our own program and raise it if needed.

We can do it using the raise statement. The raise statement in Python is used to raise or throw an exception explicitly. It can be useful for several reasons, such as:

  • to indicate that an error has occurred, and the program cannot continue for further execution.
  • to create user-defined exceptions that are specific to our application program.

Syntax to Raise Exception in Python


In Python programming, an exception can be a string, class, or an object. Most of the exceptions that Python raises are classes, with an argument that is an instance of the corresponding exception class. The common syntax to raise an exception in the Python program using raise statement (followed by the exception object) is as follows:

raise ExceptionType or String[message/argument[, traceback]]

In the above syntax,

  • raise is a keyword that is used to throw or raise an exception.
  • ExceptionType is the type of exception (for example, ZeroDivisionError) that is an object of an exception class. You can also use your own string when raising an error.
  • argument is a parameter or value to the class constructor. This argument is optional. If we do not pass any argument, then the exception argument is None.
  • argument can also be a short message in a string form
    explaining the error.
  • There is always a traceback part when any exception occurs at a runtime. The argument, traceback is also optional. However, we rarely use in the programming.

For example,

raise ZeroDivisionError("A number divided by zero is illegal in Python ")

In order to catch and handle exception using raise statement, we need to use except block, which is already we have discussed.

Example Program based on Raising an Exception


Let’s take some important example programs in which we will understand how an exception defined using raise statement can be used.

Example 1:

try:
    raise MemoryError("My memory error")
except MemoryError as me:
    print(me)
Output:
       My memory error

In this example, we have defined a try block in which we have raised an exception with a custom error message: “My memory error” using raise statement. The except block catches and handles the exception that occurs within the corresponding try block. To access the value of exception, we have used “as” keyword. “me” is a reference variable which stores the value of the exception.


Example 2:

# Raising an exception
x = int(input("Enter a positive number: "))
try:
    if x <= 0:
        raise ValueError("It is not a positive number")
except ValueError as ve:
    print(ve)
else:
    print("Positive number: ", x)
Output:
       Enter a positive number: -5
       It is not a positive number

In this example, we have prompted the user to enter a number through the input() function. Then, we have converted the entered value to an integer using int() and stored in the variable x. The code inside the try block checks whether the value of x is less than or equal to zero.


If x is less than or equal to zero, we have explicitly raised a ValueError exception using the raise statement. This error indicates that the entered number is not positive. The except block catches the ValueError exception and prints the error message associated with the exception.

If no exception is raised inside the try block, meaning x is a positive number, the else block executes. Inside the else block, it prints a message along with the positive number entered by the user.

Example 3:

# Raising an exception
num = [10, 20, 30, 40, 50]
x = 6
try:
    if x > len(num):
        raise IndexError("Index out of range: The index provided exceeds the length of the list.")
except IndexError as e:
    print(e)
else:
    print(num[x])
Output:
       Index out of range: The index provided exceeds the length of the list.

In this example, we have created a list of five numbers and assigned it to a variable named num. Then, we have assigned a value 6 to a index variable x. Inside the try block, the if statement checks that the value of x exceeds the length of the list num using the len() function.

If the value of x is greater or equal to the length of the list, it raises an IndexError with a specific error message using the raise statement. The except block catches and handles the IndexError exception if it occurs during the execution of the try block.

If no exception occurs within the try block, indicating that x is within the valid range of the list, the code proceeds to the else block. Inside the else block, it attempts to access the element at the index x in the list num.

Example 4:

# Define a custom exception class
class CustomError(Exception):
    def __init__(self, message):
        self.message = message

def check_value(value):
    if value < 0:
        raise CustomError("Value cannot be negative.")

try:
    user_input = int(input("Enter a number: "))
    check_value(user_input)
    print("Value is:", user_input)
except CustomError as ce:
    print("Custom Error:", ce.message)
except ValueError:
    print("Please enter a valid number.")
Output:
       First run:
       Enter a number: 2
       Value is: 2

       Second run:
       Enter a number: -2
       Custom Error: Value cannot be negative.

In this tutorial, we have discussed how to raise an exception in Python with the help of various example programs. Hope that you will have understood the basic concept of raising an exception and practiced all programs.
Thanks for reading!!!