Image by Author | Created on Canva
Â
In Python, you can use exceptions to anticipate and handle errors that disrupt the normal flow of a program. While Python offers many built-in exceptions—common exceptions like ValueError
, TypeError
, and KeyError
—there are cases where custom exceptions are necessary for handling unique error conditions specific to your application.
Creating custom exceptions improves both code readability and maintainability. These also facilitate easier debugging by allowing you to handle errors specific to your application—when the built-in exceptions may be too generic.
In this tutorial, we’ll learn how to create custom exceptions in Python by coding a simple e-commerce inventory system.
Â
Creating Custom Exceptions in Python
Â
You can create a custom exception in Python by subclassing the built-in Exception
class.
class MyCustomError(Exception):
"""Custom exception for a specific error"""
pass
Â
Now, let’s implement custom exceptions for an example inventory management system.
Â
Creating Custom Exceptions for an E-Commerce Inventory System
Â
You can follow along with the code for this tutorial is on GitHub.
We’ll simulate a simple e-commerce inventory system and create custom exceptions for the following cases:
- Product out of stock: When a product is unavailable.
- Invalid product ID: When the product ID doesn’t exist.
- Purchase limit exceeded: When the user attempts to buy more than the allowed quantity.
Â
Define Custom Exception Classes
We’ll define three custom exceptions to handle these cases:
OutOfStockError
: Raised when a product is out of stock; when its count drops to zero.InvalidProductIDError
: Raised when the provided product ID is invalid or doesn’t exist in the inventory.PurchaseLimitExceededError
: Raised when a user tries to exceed the allowed purchase limit for a product.
class OutOfStockError(Exception):
"""Exception raised when the product is out of stock"""
def __init__(self, product_name):
self.product_name = product_name
super().__init__(f"'self.product_name' is out of stock")
class InvalidProductIDError(Exception):
"""Exception raised for invalid product IDs"""
def __init__(self, product_id):
self.product_id = product_id
super().__init__(f"Product ID 'self.product_id' is not valid")
class PurchaseLimitExceededError(Exception):
"""Exception raised when purchase limit is exceeded"""
def __init__(self, product_name, limit):
self.product_name = product_name
self.limit = limit
super().__init__(
f"Cannot purchase more than self.limit units of 'self.product_name'"
)
Â
Set Up an Inventory Class
Next, we’ll create an Inventory
class to simulate product availability, stock levels, and purchase limits.
class Inventory:
def __init__(self):
self.products =
'P001': 'name': 'Laptop', 'stock': 5, 'max_purchase_limit': 2,
'P002': 'name': 'Smartphone', 'stock': 0, 'max_purchase_limit': 5,
Â
The products
dictionary contains product IDs with associated product names, available stock, and purchase limits.
Implement Purchase Logic and Raise Custom Exceptions
Next, we’ll add a purchase
method to the Inventory
class that checks for valid product IDs, stock availability, and purchase limits. Based on these conditions, custom exceptions will be raised.
def purchase(self, product_id, quantity):
if product_id not in self.products:
raise InvalidProductIDError(product_id)
product = self.products[product_id]
if product['stock'] == 0:
raise OutOfStockError(product['name'])
# Check if the quantity exceeds the max purchase limit
if quantity > product['max_purchase_limit']:
raise PurchaseLimitExceededError(product['name'], product['max_purchase_limit'])
# Process purchase
if quantity
Â
The method checks whether the product ID exists. If not, it raises an InvalidProductIDError
. If the product is out of stock, it raises an OutOfStockError
.
If the requested quantity exceeds the limit, it raises a PurchaseLimitExceededError
. If all conditions are met, it decreases the stock and prints a success message.
Â
Test and Handle Exceptions
Now let’s test the system with different scenarios, handling the exceptions as needed.
As seen, we handle the exceptions using try-except
blocks and print the corresponding error messages.
# Testing the system
inventory = Inventory()
try:
inventory.purchase('P001', 1) # Successful purchase
inventory.purchase('P002', 1) # OutOfStockError
except OutOfStockError as e:
print(f"Error: e")
except InvalidProductIDError as e:
print(f"Error: e")
except PurchaseLimitExceededError as e:
print(f"Error: e")
Â
We attempt to purchase one unit of a laptop (P001), which succeeds. Then, we try to purchase a smartphone (P002), which is out of stock, so it raises an OutOfStockError
.
Successfully purchased 1 unit(s) of Laptop.
Error: 'Smartphone' is out of stock
Â
Let’s also test what happens when the user tries to exceed the purchase limit.
try:
inventory.purchase('P001', 3) # PurchaseLimitExceededError
except OutOfStockError as e:
print(f"Error: e")
except InvalidProductIDError as e:
print(f"Error: e")
except PurchaseLimitExceededError as e:
print(f"Error: e")
Â
Here, we try to buy three units of a laptop (P001), but the limit is only two. This raises a PurchaseLimitExceededError
, which is caught and handled.
Error: Cannot purchase more than 2 units of 'Laptop'
Â
Wrapping Up
Â
Custom exceptions are an effective way to manage specific error conditions in your Python applications. In this tutorial, we defined custom exceptions for an e-commerce inventory system. To sum up:
- Custom exceptions allow you to describe errors in a (much) more meaningful way than generic exceptions, improving code readability.
- You can identify and isolate issues more easily when errors are tailored to specific situations.
- You can group related errors under one exception class or handle each differently based on the use case.
The code for this tutorial is on GitHub. Now that you’ve learned the basics, try implementing custom exceptions in your own projects to manage application-specific errors. Happy coding!
Â
Â
Bala Priya C is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she’s working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.
Our Top 3 Course Recommendations
1. Google Cybersecurity Certificate – Get on the fast track to a career in cybersecurity.
2. Google Data Analytics Professional Certificate – Up your data analytics game
3. Google IT Support Professional Certificate – Support your organization in IT