Paul's Python CoursePPC

Raising errors

Not met yet

raise ValueError("line 4: expected 4 parts") stops the program on purpose, with your own message. Raise when a function is handed something it can't sensibly deal with, and say exactly what and where. The caller can catch it like any other error; if nobody does, the program stops with your message at the bottom of the traceback.

Try it

main.py
def parse_level(text):
    level = text.strip().upper()
    if level not in ("INFO", "WARN", "ERROR"):
        raise ValueError(f"unknown level {level}")
    return level


print(parse_level(" warn "))
print(parse_level("loud"))

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks raise just prints its message and lets the program carry on.
  • Thinks raise hands the error back to the caller as an ordinary value, the way return does.

Where it comes up