raise (Python)

The raise statement deliberately triggers an exception, signaling that something has gone wrong. It is used to enforce rules or report invalid input in your own code.

Python

Examples

Python

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

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

Output:

age cannot be negative

Learn it in a lesson

See also

Back to the Dictionary