Custom Error Handling
Defining Custom Exceptions
Custom error handling allows developers to create domain-specific exceptions that provide more meaningful and contextual error information.
Creating Custom Exception Classes
class CustomError(Exception):
"""Base class for custom exceptions"""
def __init__(self, message):
self.message = message
super().__init__(self.message)
class ValidationError(CustomError):
"""Specific error for data validation issues"""
pass
class ResourceError(CustomError):
"""Error related to resource management"""
pass
Exception Hierarchy and Types
| Exception Type |
Purpose |
Characteristics |
| Base Custom Exception |
Generic custom error |
Inherits from Exception |
| Specific Custom Exceptions |
Domain-specific errors |
Provides detailed context |
| Hierarchical Exceptions |
Organized error handling |
Supports inheritance |
Custom Error Workflow
graph TD
A[Identify Error Condition] --> B[Create Custom Exception]
B --> C{Raise Exception}
C --> D[Catch and Handle]
D --> E[Log or Respond]
Advanced Custom Error Handling
class DataProcessor:
def validate_data(self, data):
if not data:
raise ValidationError("Empty data not allowed")
if len(data) < 3:
raise ValidationError("Insufficient data points")
return True
def process_data():
processor = DataProcessor()
try:
## Simulating data processing
data = []
processor.validate_data(data)
except ValidationError as ve:
print(f"Validation Failed: {ve.message}")
except Exception as e:
print(f"Unexpected error: {e}")
## Custom error with additional attributes
class NetworkError(Exception):
def __init__(self, message, error_code=None):
self.message = message
self.error_code = error_code
super().__init__(self.message)
def network_operation():
try:
## Simulated network failure
raise NetworkError("Connection timeout", error_code=504)
except NetworkError as ne:
print(f"Network Error: {ne.message}")
print(f"Error Code: {ne.error_code}")
Error Propagation and Chaining
def complex_operation():
try:
result = perform_risky_task()
except BaseException as original_error:
raise CustomError("Operation failed") from original_error
Best Practices
- Create meaningful and specific exception classes
- Include relevant information in custom exceptions
- Use exception hierarchies for organized error handling
- Provide clear error messages
At LabEx, we recommend designing custom exceptions that enhance code readability and debugging capabilities.
Key Takeaways
- Custom exceptions provide context-specific error handling
- Inherit from base Exception class
- Add custom attributes and methods
- Use for domain-specific error scenarios