Error Handling Patterns
Basic Exception Handling
Try-Except Block
def read_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"File {filename} not found")
except PermissionError:
print("Permission denied to read the file")
except Exception as e:
print(f"Unexpected error: {e}")
Exception Handling Strategies
Pattern |
Description |
Use Case |
Specific Catching |
Handle known exceptions |
File operations |
Generic Catching |
Catch all unexpected errors |
Fallback mechanism |
Logging |
Record error details |
Debugging |
Reraise |
Propagate exceptions |
Complex error handling |
Advanced Error Handling Techniques
Context Managers
class DatabaseConnection:
def __enter__(self):
## Setup database connection
return self
def __exit__(self, exc_type, exc_value, traceback):
## Close database connection
if exc_type is not None:
print(f"An error occurred: {exc_type}")
return False
def database_operation():
try:
with DatabaseConnection() as db:
## Perform database operations
pass
except Exception as e:
print(f"Database error: {e}")
Error Handling Flow
graph TD
A[Start Operation] --> B{Try Block}
B --> |Success| C[Complete Operation]
B --> |Exception| D[Catch Specific Exception]
D --> E{Handle Exception}
E --> |Resolve| F[Continue Execution]
E --> |Cannot Resolve| G[Raise/Log Error]
Custom Exception Handling
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(input_data):
try:
if not input_data:
raise CustomValidationError("Empty input", 400)
## Process input
except CustomValidationError as e:
print(f"Validation Error: {e.message}")
print(f"Error Code: {e.error_code}")
Recommended Practices
- Use specific exception types
- Provide clear error messages
- Log exceptions for debugging
- Handle exceptions at appropriate levels
- Avoid broad exception catching
Combining Error Handling Techniques
import logging
logging.basicConfig(level=logging.ERROR)
def complex_operation(data):
try:
## Perform complex processing
result = process_data(data)
return result
except ValueError as ve:
logging.error(f"Value Error: {ve}")
raise
except TypeError as te:
logging.error(f"Type Error: {te}")
return None
except Exception as e:
logging.error(f"Unexpected error: {e}")
## Optionally re-raise or handle
At LabEx, we emphasize robust error handling as a critical skill in Python programming, enabling developers to create more resilient and maintainable code.