
When Things Break
Sometimes Python is asked to do something impossible, like turning
the word "lots" into a number. When that happens it raises an
exception: it stops the program and prints a traceback.
fuel = int("lots")
Traceback (most recent call last):
File "main.py", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'lots'
The last line is the most useful: the exception type
(ValueError) and a message explaining what went wrong.
Catching an exception
Wrap the risky code in try. If a matching exception happens,
Python jumps to the except block instead of crashing:
try:
fuel = int("lots")
print("Got", fuel) # skipped!
except ValueError:
fuel = 0
print("That wasn't a number, using 0")
As soon as a line inside try fails, the rest of the try block is
skipped and the except block runs. The program then carries on.
Pip tip: Only wrap the lines that can actually fail. A small
tryblock makes it obvious what you are protecting against.
Assignment
Lantern keepers type their fuel readings, and they are not always numbers.
- Complete
parse_fuel(text)so it returnsint(text). - If
textcan't be converted (aValueError), return0instead of crashing.
Lantern keepers type their fuel readings, and they are not always numbers.
- Complete
parse_fuel(text)so it returnsint(text). - If
textcan't be converted (aValueError), return0instead of crashing.
Press Run to try your code, then Check to test it.