Best Practices
Exception Handling Strategies
1. Be Specific with Exception Types
## Bad Practice
try:
## Some code
pass
except:
pass
## Good Practice
try:
file = open('data.txt', 'r')
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
Exception Handling Patterns
Practice |
Recommendation |
Example |
Specific Exceptions |
Catch precise exception types |
except ValueError |
Logging |
Log exceptions for debugging |
logging.error(str(e)) |
Clean Resources |
Use finally for cleanup |
file.close() in finally |
Resource Management
def safe_file_operation():
try:
with open('data.txt', 'r') as file:
data = file.read()
## Process data
except IOError as e:
## Handle file-related errors
print(f"File error: {e}")
Exception Flow Control
graph TD
A[Start] --> B{Try Block}
B --> |Normal Execution| C[Process Data]
B --> |Exception Occurs| D{Handle Exception}
D --> |Log| E[Log Error]
D --> |Recover| F[Alternative Action]
D --> |Reraise| G[Propagate Exception]
Custom Exception Design
class ValidationError(Exception):
"""Custom exception for input validation"""
def __init__(self, message, error_code=None):
self.message = message
self.error_code = error_code
super().__init__(self.message)
def validate_user_input(value):
if not value:
raise ValidationError("Input cannot be empty", error_code=400)
- Avoid catching all exceptions
- Use exception handling for exceptional cases
- Minimize code within
try
blocks
Contextual Error Handling
def complex_operation():
try:
## Perform complex task
result = process_data()
except ValueError as ve:
## Specific error handling
log_error(f"Value error: {ve}")
return None
except Exception as e:
## Generic error fallback
log_critical_error(e)
raise
else:
## Successful execution
return result
Recommended Practices
- Use context managers (
with
statement)
- Log exceptions with detailed information
- Create meaningful custom exceptions
- Handle exceptions at appropriate levels
At LabEx, we emphasize writing clean, robust exception handling code that improves application reliability and maintainability.