Catching the right error — not 'anything that goes wrong' — step 9 of 9
One last thing before we move on. Same surface as a write step — but the lesson doesn't complete until this passes.
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 lines, three failure modes:
prices[item]raisesKeyErrorif the item isn't in the catalog.int(qty_text)raisesValueErrorif 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.
Fix it: catch KeyError and ValueError together with a tuple, return
the string "invalid" for either case, and let any other exception fly
through.
Expected output:
20
invalid
invalid
One last thing before we move on. Same surface as a write step — but the lesson doesn't complete until this passes.
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 lines, three failure modes:
prices[item]raisesKeyErrorif the item isn't in the catalog.int(qty_text)raisesValueErrorif 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.
Fix it: catch KeyError and ValueError together with a tuple, return
the string "invalid" for either case, and let any other exception fly
through.
Expected output:
20
invalid
invalid
this step needs the editor
on desktop today; in the app (coming soon). save your spot and we'll bring you back here when you're ready.