Code

Raise the Alarm

Your own functions can raise exceptions too. Use raise when the caller gave you something you can't work with:

def set_brightness(level):
    if not 0 <= level <= 100:
        raise ValueError(f"Must be 0-100, got {level}")
    return level

raise stops the function right away, just like a crash. The caller can catch it with try / except ValueError.

A good message says what was wrong. It also shows which value caused it.

Your own kind of error

Sometimes no built-in exception fits. You can make a new one with this two-line recipe:

class LanternError(Exception):
    pass

Here is what each part means:

  • class LanternError makes a new type with that name. (You'll learn all about classes later, in Objects & Classes.)
  • (Exception) says "this is a kind of exception". So raise and except work with it, just like with ValueError.
  • pass means "nothing else to add".

Then use it like any other exception:

try:
    raise LanternError("The wick is gone")
except LanternError as err:
    print("Problem:", err)   # Problem: The wick is gone

A custom name makes errors easy to spot and easy to catch.

Assignment

  1. Use the recipe to define OutOfFuelError.
  2. In burn(fuel, hours), if hours is negative, raise a ValueError. Its message must contain the word hours.
  3. If hours is more than fuel, raise OutOfFuelError(f"Need {hours} fuel but only have {fuel}").
  4. Otherwise, return fuel - hours.