Best Error Practices
Error Handling Principles
1. Specific Exception Handling
def read_file(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
print(f"File {filename} not found")
except PermissionError:
print(f"No permission to read {filename}")
Error Logging Strategies
Implementing Comprehensive Logging
import logging
## Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s: %(message)s',
filename='app_errors.log'
)
def critical_operation():
try:
## Risky operation
result = complex_calculation()
except Exception as e:
logging.error(f"Operation failed: {e}", exc_info=True)
Error Prevention Techniques
def validate_user_input(value):
if not isinstance(value, (int, float)):
raise TypeError("Input must be a number")
if value < 0:
raise ValueError("Value cannot be negative")
return value
Error Handling Workflow
graph TD
A[Start Operation] --> B{Input Validation}
B --> |Valid| C[Execute Operation]
B --> |Invalid| D[Raise Specific Exception]
C --> E{Operation Successful?}
E --> |Yes| F[Return Result]
E --> |No| G[Log Error]
G --> H[Handle/Recover]
Best Practices Checklist
| Practice |
Description |
Example |
| Specific Exceptions |
Catch precise exception types |
except ValueError |
| Minimal Try Blocks |
Keep try blocks focused |
Avoid large code blocks |
| Logging |
Record error details |
Use logging module |
| Graceful Degradation |
Provide fallback mechanisms |
Return default values |
Advanced Error Management
Context Managers
from contextlib import contextmanager
@contextmanager
def error_handler():
try:
yield
except Exception as e:
print(f"Managed error: {e}")
## Optional: additional error handling logic
with error_handler():
## Risky operation
result = 10 / 0
- Avoid using exceptions for flow control
- Minimize nested try-except blocks
- Use
traceback for detailed error information
import traceback
def detailed_error_reporting():
try:
## Complex operation
raise RuntimeError("Demonstration error")
except Exception:
traceback.print_exc()
Error Monitoring and Reporting
Implementing Error Tracking
class ErrorTracker:
def __init__(self):
self.error_count = 0
def track_error(self, error):
self.error_count += 1
print(f"Error tracked: {error}")
def get_error_summary(self):
return f"Total errors: {self.error_count}"
Conclusion
Effective error handling is an art of balancing robust code with clean, maintainable implementations. LabEx recommends continuous practice and learning to master these techniques.