PythiloLesson 23 of 30 · progress kept in this browser

Errors and try/except

An exception stops normal flow and travels up the call stack until something handles it.

def to_int(text):
    try:
        return int(text)
    except ValueError:
        return None
  • try holds the code that might fail.
  • except SomeError handles only that type, and its subclasses.
  • else runs if nothing was raised.
  • finally always runs, which suits cleanup.
Your task

Write parse_age(text) converting text to an int and raising ValueError if it is not a number or is outside 0 to 150. Write safe_ratio(a, b) returning a / b, or None when b is zero. Other errors must still propagate.