raise — Easy Examples
Throws an exception manually
Raising exceptions
Using raise to signal errors.
python
def divide(a, b): if b == 0: raise ZeroDivisionError("Cannot divide by zero") return a / b try: result = divide(10, 0) except ZeroDivisionError as e: print(f"Error: {e}") # Raise with a message def validate_age(age): if not isinstance(age, int): raise TypeError("Age must be an integer") if age < 0 or age > 150: raise ValueError(f"Age {age} is out of range") return age try: validate_age(-5) except ValueError as e: print(f"Validation: {e}")
Expected Output
Error: Cannot divide by zero Validation: Age -5 is out of range
raise creates and throws an exception. Always include a descriptive message to help with debugging.
Want to try these examples interactively?
Open Easy Playground