Code

A Clearer Alarm

Sometimes you catch one error and want to raise a clearer one. Add from err at the end:

class BadReadingError(Exception):
    pass

def read_hours(text):
    try:
        return int(text)
    except ValueError as err:
        raise BadReadingError(f"Bad hours: {text!r}") from err
  • The caller now sees a BadReadingError with a helpful message.
  • from err keeps the original ValueError attached, as __cause__. The traceback shows both errors, so no clue is lost.

What is !r?

Inside an f-string, {text!r} shows the value the way Python would write it in code. Strings get quotes around them:

text = "four"
print(f"Bad hours: {text}")     # Bad hours: four
print(f"Bad hours: {text!r}")   # Bad hours: 'four'

The quotes make empty strings and extra spaces easy to see.

Assignment

OutOfFuelError and burn are ready from the last lesson.

  1. Use the recipe to define BadReadingError.
  2. Complete burn_from_text(fuel, text). Convert text with int().
  3. If that fails, raise BadReadingError(f"Bad hours: {text!r}") chained from the ValueError.
  4. Otherwise, return burn(fuel, hours).