
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 LanternErrormakes a new type with that name. (You'll learn all about classes later, in Objects & Classes.)(Exception)says "this is a kind of exception". Soraiseandexceptwork with it, just like withValueError.passmeans "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
- Use the recipe to define
OutOfFuelError. - In
burn(fuel, hours), ifhoursis negative, raise aValueError. Its message must contain the wordhours. - If
hoursis more thanfuel, raiseOutOfFuelError(f"Need {hours} fuel but only have {fuel}"). - Otherwise, return
fuel - hours.
- Use the recipe to define
OutOfFuelError. - In
burn(fuel, hours), ifhoursis negative, raise aValueError. Its message must contain the wordhours. - If
hoursis more thanfuel, raiseOutOfFuelError(f"Need {hours} fuel but only have {fuel}"). - Otherwise, return
fuel - hours.
main.py Python sleeping
Press Run to try your code, then Check to test it.