Python | raise keyword

Python | raise keyword

In Python, the raise keyword plays a crucial role in exception handling. It empowers developers to explicitly raise exceptions, providing a way to indicate that an error or exceptional situation has occurred during the execution of a program. This article go into the complexity of the raise keyword, exploring its syntax, use cases, and providing examples to illustrate its importance in Python programming.

The raise keyword in Python is used to raise an exception explicitly. When an exception is raised, it interrupts the normal flow of the program and transfers control to the nearest exception-handling block. The basic syntax of the raise statement is as follows:

raise ExceptionType("Error message")

Here, ExceptionType is the type of exception to be raised, and the optional “Error message” provides additional information about the exception.

Example 1: Raising a Custom Exception:
Let’s start with a simple example of using the raise keyword to raise a custom exception:

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

try:
    result = divide(10, 0)
except Exception as e:
    print(f"Error: {e}")

Output:

raise_keyword_example_1
raise_keyword_example_1

In this example, the divide function raises a custom exception with a specific error message when attempting to divide by zero. The try-except block then catches the raised exception and prints the error message.

Example 2: Raising Built-in Exceptions:
The raise keyword is not limited to custom exceptions; it can also be used to raise built-in exceptions:

def validate_age(age):
    if not 0 <= age <= 120:
        raise ValueError("Invalid age value")

try:
    validate_age(150)
except ValueError as e:
    print(f"Error: {e}")

Output:

raise_keyword_example_2
raise_keyword_example_2

Here, the validate_age function raises a ValueError if the provided age is outside the valid range (0 to 120). The try-except block catches the exception and prints the error message.

Example 3: Raising Exception from Exception Handler:
You can also use the raise keyword within an exception handler to re-raise the caught exception:

def safe_divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        raise ValueError("Cannot divide by zero")
    return result

try:
    result = safe_divide(10, 0)
except ValueError as e:
    print(f"Error: {e}")

Output:

raise_keyword_example_3
raise_keyword_example_3

Here, the safe_divide function catches a ZeroDivisionError and re-raises it as a ValueError with a more informative message.

Example 4: Raising Exception for Invalid Input:

def calculate_area(length, width):
    if length <= 0 or width <= 0:
	    raise ValueError("Length and width must be positive values.")
	return length * width
	
calculate_area(10, 0)

Output:

raise_keyword_example_4
raise_keyword_example_4

Here, calculate_area function raises an exception if either Length or Width having negative value.

Example 5: Raising last active exception:
Raising last active exception using raise keyword without any argument.

try:
	result = 42 / 0
except Exception as error:
	print("Exception need to be raised")
	raise

Output:

raise_keyword_example_5
raise_keyword_example_5

Here, raising last active exception (ZeroDivisionError).

Note: raise keyword can be used independently. No need to used along with try-except code block.

Conclusion:
The raise keyword in Python is a powerful tool for handling exceptions and signaling exceptional conditions in your code. Whether you’re raising built-in exceptions or creating custom ones, using raise allows you to communicate errors effectively and handle them appropriately.

Leave a Reply

Your email address will not be published. Required fields are marked *

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds