🎓 A1Learner
🔍
0 of 52 lessons completed

Python Writing Helpful Error Messages

A helpful error message names the value and the rule it broke. The reader then knows what to fix.

A vague message helps no one

The age -3 is bad. The message says only Bad age.

def set_age(age):
    if age < 0:
        raise ValueError("Bad age")

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

Name the value and the rule

The message names -3 and the rule. The reader knows what to fix.

def set_age(age):
    if age < 0:
        raise ValueError(f"Age is {age}, but age must be 0 or more")

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

A message with a big score

The score 120 is too big. The message names 120 and the limit.

def set_score(score):
    if score > 100:
        raise ValueError(f"Score is {score}, but score must be 100 or less")

try:
    set_score(120)
except ValueError as e:
    print(e)

Good values pass through

The age 30 breaks no rule. The function hands it back.

def set_age(age):
    if age < 0:
        raise ValueError(f"Age is {age}, but age must be 0 or more")
    return age

print(set_age(30))

Example

def book_seats(count):
    if count < 1:
        raise ValueError(f"Seats is {count}, but seats must be 1 or more")
    if count > 6:
        raise ValueError(f"Seats is {count}, but seats must be 6 or less")
    return count

for count in [0, 3, 9]:
    try:
        print("Booked:", book_seats(count))
    except ValueError as e:
        print(e)

Key points

  • Error message: the text that comes with a raised error
  • Use raise ValueError to report a bad value
  • Name the bad value inside the message
  • Name the rule the value broke
  • A vague message says only that something failed
  • A clear message saves a search through the code

In this example, book_seats checks each count. The count 0 breaks the low rule. The count 3 breaks no rule, so it books. The count 9 breaks the high rule. Each message names its count and its rule.

Note

A raised error stops the program unless caught.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which message helps the reader most?