7.3 Raising Exceptions (raise)

7.3 Raising Exceptions (raise)

We learn how to explicitly raise exceptions with the raise keyword to enforce rules and manage application logic.

Sometimes, we don't just want to handle the errors Python raises, but to create our own. The `raise` statement allows us to explicitly raise (or "throw") an exception at any time. This is extremely useful for enforcing business rules and signaling invalid states in our code.
# Example: Raising a built-in exception
def calculate_square_root(number):
    if number < 0:
        raise ValueError("Cannot calculate the square root of a negative number.")
    return number ** 0.5

try:
    print(f"Square root of 25: {calculate_square_root(25)}")
    # The line below will raise the exception
    print(f"Square root of -9: {calculate_square_root(-9)}")
except ValueError as e:
    print(f"Caught an error: {e}")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.