Python Mastery – From Basics to Brilliance / Exception Handling

Raising Exceptions

Sometimes, we want to manually throw an error using raise.

πŸ’‘ Example:

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

try:
    set_age(-1)
except ValueError as e:
    print("Error:", e)

βœ… Raising exceptions is useful when building functions or APIs that must enforce rules.

Error: Age cannot be negative

πŸ” Real-life Analogy:

You walk into a store with no mask β†’ a guard stops you (raises exception) and redirects politely.