Built-in exceptions cover many general failures, but real projects also have business-rule failures. “Out of stock” is not a syntax or type error; it means a domain rule was violated.
Defining an exception class
A custom exception normally inherits Exception. A simple class may initially contain only pass, with a detailed message supplied at the raise site. Its name should express the failure clearly, allowing callers to recognize the category without parsing message text.
class OutOfStockError(Exception):
pass
raise OutOfStockError("Notebook is out of stock.")KNOWLEDGE QUIZ
Stock example
ValueError means the purchase quantity itself is invalid. OutOfStockError means the quantity is sensible but current inventory cannot satisfy it. The types express different levels of failure.
class OutOfStockError(Exception):
pass
class Product:
def __init__(self, name, stock):
self.name = name
self.stock = stock
def purchase(self, quantity):
if quantity <= 0:
raise ValueError("Quantity must be greater than 0.")
if quantity > self.stock:
raise OutOfStockError("%s is out of stock." % self.name)
self.stock -= quantity
product = Product("Notebook", 5)
try:
product.purchase(3)
print("Remaining stock:", product.stock)
product.purchase(4)
except OutOfStockError as error:
print("Purchase failed:", error)Remaining stock: 2
Purchase failed: Notebook is out of stock.KNOWLEDGE QUIZ
Why custom exceptions matter
The value of a custom exception is semantics. After catching OutOfStockError, a UI can offer restocking or another product. After ValueError, it should request a different quantity. Caller code can also log, retry, or re-raise these failures separately.
| Error | Meaning | Possible response |
|---|---|---|
ValueError | Invalid argument | Request new input |
OutOfStockError | Insufficient stock | Restock or change product |
KNOWLEDGE QUIZ
Define IllegalTriangleError
- Define IllegalTriangleError as an Exception subclass.
- Triangle.__init__ raises ValueError for non-positive sides.
- Raise IllegalTriangleError when the triangle inequality fails.
- Catch the two exception types separately and print different messages.