raise

KeywordPython 2.0+Beginner

Throws an exception manually

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

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}")

raise creates and throws an exception. Always include a descriptive message to help with debugging.

Try in Playground

Tags

languagesyntaxcoreerror-handlingexception

Related Items