Code

Catch the Right One

One try can have several except blocks. Python checks them top to bottom and runs the first one that matches.

prices = {"oil": 3, "wick": 1}
try:
    qty = int(input("How many? "))
    cost = prices["glass"] * qty
except ValueError:
    print("Please type a whole number.")
except KeyError as err:
    print("We don't sell", err)
  • except KeyError as err: stores the exception object in err, so you can print or inspect its message.
  • You can catch several types with one block: except (ValueError, KeyError):.
  • Anything you don't list is not caught, and that's a good thing! Unexpected errors should stay loud so you notice bugs.

Assignment

A shelf is a list of items. Players pick a slot by typing a number.

  1. Complete read_slot(shelf, choice): convert choice with int() and return the item at that index of shelf.
  2. If choice isn't a whole number (ValueError), return "Not a number".
  3. If there's no item at that index (IndexError), return "Empty slot".
  4. Don't catch any other exception types.