
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
BadReadingErrorwith a helpful message. from errkeeps the originalValueErrorattached, 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.
- Use the recipe to define
BadReadingError. - Complete
burn_from_text(fuel, text). Converttextwithint(). - If that fails, raise
BadReadingError(f"Bad hours: {text!r}")chainedfromtheValueError. - Otherwise, return
burn(fuel, hours).
OutOfFuelError and burn are ready from the last lesson.
- Use the recipe to define
BadReadingError. - Complete
burn_from_text(fuel, text). Converttextwithint(). - If that fails, raise
BadReadingError(f"Bad hours: {text!r}")chainedfromtheValueError. - Otherwise, return
burn(fuel, hours).
main.py Python sleeping
Press Run to try your code, then Check to test it.