Editor

Build a Shopping Cart Exception Hierarchy

Advanced · Write the code · from Python Custom Exceptions: Build Your Own Error Types

From the lesson: Python Custom Exceptions: Build Your Own Error Types

Imagine your car's dashboard had only one warning light that just said "Problem." Not very helpful, right? You'd want to know: is the engine overheating? Is the oil low? Is a door open? The more specific the warning, the faster you can fix the issue.

Read the lesson

Create an exception hierarchy for a shopping cart:

1. CartError(Exception) - base class (just pass)

2. EmptyCartError(CartError) - just pass

3. ItemNotFoundError(CartError) - accepts item_name in __init__, stores it as self.item_name, message: "Item not found: X"

Then write a function checkout(cart) that:

  • Raises EmptyCartError("Cart is empty") if the cart list is empty
  • Prints "Checking out N items" where N is the number of items
  • And a function remove_item(cart, item) that:

  • Raises ItemNotFoundError(item) if the item is not in the cart
  • Otherwise removes it and prints "Removed: X"
  • Test:

    1. Call checkout([]) and catch EmptyCartError

    2. Call remove_item(["apple", "bread"], "milk") and catch ItemNotFoundError, printing the item_name attribute

    3. Call checkout(["apple", "bread"]) (success)

    # Build the exception hierarchy
    # Write checkout and remove_item functions
    # Test all three cases

    More Custom Exceptions exercises

    All Python exercises · 50 practice problems · Error Handling quiz