Skip to content
Home / Fundamentals

How to Manually Raise an Exception in Python

In Python, you can manually raise an exception by using the raise statement. The raise statement allows you to throw an exception at any point in your code, interrupting the normal flow of execution and signaling that something has gone wrong.

Here's an example of how to raise an exception in Python:

def divide(x, y):
    if y == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return x / y

print(divide(10, 2))  # Output: 5.0
print(divide(10, 0))  # Output: ZeroDivisionError: Cannot divide by zero

In this example, we have a function divide that divides two numbers. If the second argument is zero, the function raises a ZeroDivisionError exception with the message "Cannot divide by zero".

The raise statement takes an exception object as its argument. In the example above, we created a ZeroDivisionError object and passed it to the raise statement. You can also create your own custom exception objects by subclassing the Exception class.

Here's an example of how to create a custom exception:

class MyCustomError(Exception):
    def __init__(self, message):
        self.message = message

def raise_error():
    raise MyCustomError("This is my custom error")

try:
    raise_error()
except MyCustomError as e:
    print(e.message)  # Output: "This is my custom error"

In this example, we created a custom exception class called MyCustomError that subclasses the Exception class. We then defined a init method that takes a message as an argument and assigns it to the message attribute of the object.

To raise this custom exception, we called the raise statement with an instance of MyCustomError as its argument. We then caught the exception using a try-except block and printed the message attribute of the exception object.