promptdojo_promptdojo_promptdojo_promptdojo_promptdojo_promptdojo_promptdojo_promptdojo_promptdojo_promptdojo_promptdojo_

try/except — the patterns AI misuses — step 8 of 8

Checkpoint

One last thing before we move on. pass this to mark the lesson done, or skip and keep moving. hop to the next when you're ready.

Last drill. Cursor wrote summarize_order to look up an item's price, multiply it by a quantity it parses from a string, and return a total. Three failure modes:

  • prices[item] raises KeyError if the item isn't in the catalog.
  • int(qty_text) raises ValueError if the string isn't a number.
  • everything else (a real bug you didn't anticipate) should crash.

The starter has a single except Exception: that swallows all three. The last order in the list is a real bug — the caller passed a list instead of an item name, which raises TypeError. The test harness at the bottom catches that and prints bug: crashed loudly so you can see the bug escaping. Right now it prints invalid instead — the broad except is hiding it.

Fix the except: catch KeyError and ValueError together with a tuple, return "invalid" for either case, and let any other exception fly through.

Expected output:

20
invalid
invalid
bug: crashed loudly

full-screen editor opens — close anytime to keep reading.