Python Raise Keyword – Raise an Exception in Python

Python Raise Keyword

In Python, you can manually raise exceptions using the raise keyword. While Python automatically raises built-in exceptions when something goes wrong, there are times when you may want to trigger an exception yourself.

Why Use raise?

The raise keyword allows you to generate exceptions at specific points in your code. This is especially useful in conditional blocks where you may want to enforce specific rules or validate input.

Syntax:

				raise <exception>

			

When the raise statement is executed, the specified exception is triggered immediately, and the program halts unless the exception is caught in a try/except block.

Example:

				var = 10
print("Var =", var)
raise ValueError
print("Program execution continues...")

			
Python raise exceptions

n this example, the program raises a ValueError and halts execution. The raise keyword forces the exception to occur, regardless of whether an actual error exists.

Using raise in try/except Blocks

You can also use the raise keyword inside a try block to test exception handling. This is helpful to ensure that your exception handling code is working correctly.

Example:

				try:
    var = 10
    print("Var =", var)
    raise ValueError
except ValueError:
    print("Oops!! Value error raised")
print("Program execution continues...")

			
Python raise exception in try and except block

Testing Exceptions with raise

Using the raise keyword within a try/except block is a great way to test your exception handling without involving actual user input.

For example, if you expect a ValueError to occur during division, you can manually raise it to verify your handling code.

Example:

				try:
    N1 = int(input("Enter first Number – N1 :"))
    N2 = int(input("Enter Second Number – N2 :"))
    Result = N1 / N2
    print("Result:", Result)
    raise ValueError
except ValueError:
    print("Oops!! Seems you have entered an invalid Number")
print("Program execution continues...")

			
Python Exceptions with raise keyword

Even though correct inputs were provided, the ValueError is triggered due to the raise statement, demonstrating how the try/except block handles exceptions.

Summary

The raise keyword in Python allows you to manually trigger exceptions at specific points in your code. This can be useful for enforcing rules, validating input, or testing exception handling in try/except blocks.

When raise is used, the program stops and throws the specified exception unless it’s caught by an exception handler. This keyword is especially valuable for simulating and managing errors during program development.

Leave a Comment