Best Practices
Error Handling Principles
1. Be Specific with Exceptions
## Bad Practice
try:
## Complex operation
pass
except:
pass
## Good Practice
try:
result = perform_complex_operation()
except (ValueError, TypeError) as e:
log_error(e)
handle_specific_error(e)
Exception Handling Strategies
Recommended Approaches
Practice |
Recommendation |
Example |
Specific Catching |
Catch specific exceptions |
except ValueError: |
Logging |
Always log exceptions |
logging.error(str(e)) |
Context Management |
Use context managers |
with open() as file: |
Context Managers for Safe Resource Handling
def safe_file_operation():
try:
with open('data.txt', 'r') as file:
content = file.read()
process_content(content)
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Access denied")
Error Propagation Flow
graph TD
A[Original Function] --> B{Exception Occurs?}
B -->|Yes| C[Catch and Handle]
C --> D[Log Error]
D --> E[Raise or Return Safely]
B -->|No| F[Continue Execution]
Custom Exception Design
class CustomValidationError(ValueError):
def __init__(self, message, error_code):
self.error_code = error_code
super().__init__(f"{message} (Code: {error_code})")
def validate_data(data):
if not data:
raise CustomValidationError("Invalid data", 400)
Defensive Programming Techniques
Error Prevention Strategies
- Input Validation
- Type Checking
- Boundary Condition Management
def safe_division(a, b):
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Numeric types required")
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
Logging Best Practices
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
def robust_function():
try:
## Complex operation
result = perform_operation()
except Exception as e:
logging.error(f"Operation failed: {e}")
raise
LabEx Recommended Workflow
At LabEx, we emphasize:
- Comprehensive error documentation
- Consistent error handling patterns
- Proactive error prevention
Error Handling Overhead
- Minimize try-except block complexity
- Avoid excessive exception catching
- Use conditional checks when possible
Key Takeaways
- Be precise in exception handling
- Log errors comprehensively
- Design clear error recovery mechanisms
- Prioritize code readability