SyntaxStudy
Sign Up
Python Beginner 3 min read

Raising Exceptions

Raising Exceptions

Use raise to trigger an exception intentionally, signalling that something is wrong in your logic.

Example
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

try:
    set_age(-5)
except ValueError as e:
    print(e)
Pro Tip

Raise exceptions to enforce business rules in your functions.