Custom Error Strategies
Creating Custom Exceptions
Defining Custom Exception Classes
class CustomValidationError(Exception):
def __init__(self, message, error_code):
self.message = message
self.error_code = error_code
super().__init__(self.message)
def validate_user_input(value):
if not isinstance(value, int):
raise CustomValidationError(
"Input must be an integer",
error_code=400
)
Exception Hierarchy and Design
graph TD
A[Base Exception] --> B[Custom Exception Class]
B --> C[Specific Error Type 1]
B --> D[Specific Error Type 2]
Advanced Error Handling Patterns
class BusinessLogicError(Exception):
"""Base class for business logic exceptions"""
pass
class InsufficientFundsError(BusinessLogicError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
message = f"Insufficient funds: Balance {balance}, Required {amount}"
super().__init__(message)
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
return self.balance
Error Handling Strategies
Strategy |
Description |
Use Case |
Logging |
Record detailed error information |
Debugging, Monitoring |
Graceful Degradation |
Provide alternative functionality |
Maintaining User Experience |
Retry Mechanism |
Attempt operation multiple times |
Transient Errors |
Context Managers for Error Handling
from contextlib import contextmanager
@contextmanager
def error_handler():
try:
yield
except Exception as e:
print(f"An error occurred: {e}")
## Perform additional error handling
## Usage
with error_handler():
## Risky operation
result = 10 / 0
def external_api_call():
try:
## Simulated API call
raise ConnectionError("Network failure")
except ConnectionError as e:
## Transform original error
raise BusinessLogicError("API Connection Failed") from e
Key Principles of Custom Error Handling
- Be specific with exception types
- Provide meaningful error messages
- Include relevant context information
- Use exception chaining when transforming errors
Best Practices
- Create a clear exception hierarchy
- Use custom exceptions for domain-specific errors
- Avoid catching too broad exceptions
- Log and handle errors appropriately
At LabEx, we believe that robust error handling is an art of creating resilient and maintainable Python applications.