Exception Management
Common File Exceptions in Python
Exception |
Description |
Typical Scenario |
FileNotFoundError |
File does not exist |
Incorrect file path |
PermissionError |
Insufficient access rights |
Restricted file access |
IOError |
Input/Output related error |
Disk issues, file corruption |
OSError |
Operating system error |
File system problems |
Comprehensive Exception Handling Strategy
def advanced_file_exception_handler(filename):
try:
## Primary file reading operation
with open(filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"Error: File {filename} does not exist")
## Logging mechanism
logging.error(f"File not found: {filename}")
return None
except PermissionError:
print(f"Error: No permission to read {filename}")
## Alternative access strategy
attempt_alternative_access(filename)
return None
except IOError as e:
print(f"IO Error occurred: {e}")
## Detailed error tracking
handle_io_error(e)
return None
except Exception as unexpected_error:
print(f"Unexpected error: {unexpected_error}")
## Comprehensive error management
log_unexpected_error(unexpected_error)
return None
Exception Handling Workflow
graph TD
A[File Reading Attempt] --> B{Try Operation}
B --> |Success| C[Process File Content]
B --> |Failure| D{Identify Exception}
D --> |File Not Found| E[Log Error]
D --> |Permission Issue| F[Check Permissions]
D --> |IO Error| G[Diagnose System Issue]
D --> |Unexpected Error| H[Comprehensive Logging]
E --> I[Alternative Strategy]
F --> I
G --> I
H --> I
Advanced Error Logging Technique
import logging
import traceback
def robust_file_error_logging(filename):
try:
with open(filename, 'r') as file:
return file.read()
except Exception as e:
## Detailed error logging
logging.error(f"Error reading {filename}: {str(e)}")
logging.error(traceback.format_exc())
## Create error report
create_error_report(filename, e)
Best Practices for Exception Management
- Always use specific exception handling
- Implement comprehensive logging
- Provide meaningful error messages
- Create fallback mechanisms
- Log detailed error information
LabEx Tip
LabEx environments provide excellent platforms to practice and understand complex exception management techniques.
Custom Exception Handling
class FileReadError(Exception):
"""Custom exception for file reading errors"""
def __init__(self, filename, message):
self.filename = filename
self.message = message
super().__init__(self.message)
def safe_file_read(filename):
try:
with open(filename, 'r') as file:
return file.read()
except Exception as e:
raise FileReadError(filename, f"Cannot read file: {e}")
Key Takeaways
- Implement multi-level exception handling
- Use specific exception types
- Log errors comprehensively
- Create fallback and recovery mechanisms
- Design user-friendly error responses