Fill in

Else and Finally

A try statement has two more optional parts:

try:
    n = int(text)          # the risky part
except ValueError:
    print("bad number")    # runs if it failed
else:
    print("got", n)        # runs only if it did NOT fail
finally:
    print("checked")       # ALWAYS runs
  • else runs only when the try block finished without an exception. It lets you keep try tiny: only the risky line goes there, and the "happy path" goes in else.
  • finally runs no matter what: success, failure, or even a return inside the other blocks. It is the place for clean-up, like closing a file or putting tools back.

The order is always try, then except, then else, then finally.

Assignment

Fill in the four ___ blanks in try_light(fuel_text) with the keywords try, except, else and finally, so that:

  1. "2.5" logs "lit with 2.5" then "checked", and returns True.
  2. "soup" logs "bad fuel" then "checked", and returns False.