error handling — when ai's code crashes mid-flight9 / 9
raising errors — making your code fail loudly on purpose
Checkpoint
One last thing before we move on. Same surface as a write step — but the lesson doesn't complete until this passes.
Last drill. Write a tiny order system:
- Define a custom exception class
OutOfStockthat inherits fromException. - Define a function
place_order(inventory, item, qty)that:- Raises
KeyError(item)ifitemis not ininventory. - Raises
OutOfStock(f"only {inventory[item]} left of {item}")ifinventory[item] < qty. - Otherwise returns the string
f"shipped {qty} {item}".
- Raises
- Loop over three orders. For each, wrap the call in
try/except (KeyError, OutOfStock) as err: print(err).
Use this inventory and these orders:
inventory = {"book": 5, "pen": 0}
orders = [("book", 2), ("pen", 1), ("hat", 1)]
Expected output:
shipped 2 book
only 0 left of pen
'hat'
⌘↵ runs the editor.
Booting Python…
Output
[promptdojo:~]$ _