Creating and Using Custom Exceptions in Python
This article explains why custom exceptions are needed in Python, shows how to define them—including simple, information‑rich, and subclassed variants—provides practical code examples such as inventory‑shortage and API‑request errors, and outlines best practices for naming, documentation, and inheritance.
In Python, exception handling is essential for robust programs. Besides built‑in exceptions such as ValueError , TypeError , and IndexError , developers can create custom exceptions to capture specific business‑logic errors more precisely.
1. Why custom exceptions?
Built‑in exceptions cover many common errors, but custom ones provide:
Clearer error classification, e.g., InsufficientStockError conveys the problem better than a generic ValueError .
Business‑logic‑specific errors, such as InvalidTransactionError in a banking system.
Improved code readability and maintainability.
2. How to define custom exceptions?
All Python exceptions must inherit from BaseException , though inheriting from Exception or its subclasses is recommended. Common implementations include:
(1) Simplest custom exception
class MyCustomError(Exception):
"""Custom exception example"""
passRaise it directly:
raise MyCustomError("A custom error occurred!")(2) Custom exception with extra information
Override __init__ to store additional context:
class ValidationError(Exception):
"""Raised when data validation fails"""
def __init__(self, message, field):
super().__init__(message) # call parent initializer
self.field = field # store field nameUsage example:
try:
raise ValidationError("Invalid username", field="username")
except ValidationError as e:
print(f"Error in field {e.field}: {e}")(3) Inheriting from an existing exception
If a built‑in exception is close to your needs, subclass it:
class PositiveNumberError(ValueError):
"""Number must be positive"""
passUsage example:
def check_positive(num):
if num <= 0:
raise PositiveNumberError(f"Number {num} must be positive!")
check_positive(-5) # triggers PositiveNumberError3. Real‑world scenarios
Scenario 1: E‑commerce insufficient stock
class InsufficientStockError(Exception):
def __init__(self, item_name, available, requested):
self.item_name = item_name
self.available = available
self.requested = requested
super().__init__(f"Item {item_name} out of stock! Available {available}, requested {requested}")
def purchase_item(item_name, stock, quantity):
if quantity > stock:
raise InsufficientStockError(item_name, stock, quantity)
print(f"Successfully purchased {quantity} of {item_name}")Test code:
try:
purchase_item("Python Book", stock=5, quantity=10)
except InsufficientStockError as e:
print(e) # Output: Item Python Book out of stock! Available 5, requested 10Scenario 2: API request failure
class APIRequestError(Exception):
"""API request failed"""
def __init__(self, url, status_code, response=None):
self.url = url
self.status_code = status_code
self.response = response
super().__init__(f"Request {url} failed, status code: {status_code}")Simulated API call:
try:
raise APIRequestError("https://api.example.com/data", 404)
except APIRequestError as e:
print(f"API error: {e}, response: {e.response}")4. Best practices
Name exception classes with an Error suffix, e.g., InvalidInputError .
Include rich information (error field, status code, etc.) to aid debugging.
Prefer inheriting from Exception or a more specific built‑in exception.
Document each custom exception with a docstring describing its purpose and trigger conditions.
5. Summary
Custom exceptions are an advanced Python technique that enables more precise error typing, richer error information, and better code readability and maintainability. By inheriting from Exception and adding tailored logic, developers can create exception types suited to diverse business scenarios, leading to more elegant and professional error handling.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.