🎓 A1Learner
🔍

Python Raise Exceptions

raise triggers an error on purpose in a program. An error raised this way has a chosen type and message.

Raise an error on purpose

raise stops the program with your message.

raise ValueError("Too small")

Reject a bad argument

The function checks its argument first.

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    print("Age is", age)

check_age(-3)

A good argument passes

No error is raised for a sensible age.

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    print("Age is", age)

check_age(21)

Assert checks a claim

assert is a quick self-check while you code. It does nothing when the claim is true.

age = 21
assert age >= 0, "Age cannot be negative"
print("Check passed")

A failed assert stops you

A false claim raises AssertionError.

score = -1
assert score >= 0, "Score cannot be negative"
print("Check passed")

Example

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    print("Age set to", age)

try:
    set_age(-5)
except ValueError:
    print("That age does not work.")
set_age(30)

Key points

  • Use raise to trigger an error on purpose
  • Give raise an error type and a clear message
  • Functions raise errors to reject bad arguments early
  • Use assert for quick checks while you develop

In this example, set_age checks the age before it accepts it. The first call passes -5 into the function. The if test spots the negative number. raise stops that call with a ValueError. The except block catches it and prints a friendly line. The second call passes 30, so no error is raised. The function prints Age set to 30.

Note

Running Python with -O switches assert checks off.

Never guard real user input with assert alone.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Inside a function, how do you reject a bad argument at once?