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 lessonCreate 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:
EmptyCartError("Cart is empty") if the cart list is empty"Checking out N items" where N is the number of itemsAnd a function remove_item(cart, item) that:
ItemNotFoundError(item) if the item is not in the cart"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)
More Custom Exceptions exercises
- Create a Custom ExceptionBeginner
- Predict the Exception HierarchyBeginner
- Exception with Extra DataIntermediate
- Refactor: Replace Generic with Custom ExceptionsAdvanced
All Python exercises · 50 practice problems · Error Handling quiz