Code

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 try block makes it obvious what you are protecting against.

Assignment

Lantern keepers type their fuel readings, and they are not always numbers.

  1. Complete parse_fuel(text) so it returns int(text).
  2. If text can't be converted (a ValueError), return 0 instead of crashing.