Error Handling Techniques
Python provides specific exceptions for handling directory operations:
Exception |
Description |
Scenario |
FileNotFoundError |
Directory does not exist |
Accessing non-existent path |
PermissionError |
Insufficient access rights |
No read/write permissions |
NotADirectoryError |
Path is not a directory |
Attempting operation on file |
OSError |
General OS-related errors |
Disk full, network issues |
Basic Exception Handling Strategies
1. Simple Try-Except Block
import os
def create_directory(path):
try:
os.makedirs(path)
print(f"Directory created: {path}")
except FileExistsError:
print(f"Directory already exists: {path}")
except PermissionError:
print(f"Permission denied: Cannot create {path}")
2. Comprehensive Error Handling
from pathlib import Path
def safe_directory_operation(path):
try:
directory = Path(path)
if not directory.exists():
directory.mkdir(parents=True, exist_ok=True)
if not directory.is_dir():
raise NotADirectoryError(f"Path is not a directory: {path}")
## Perform directory operations
return True
except PermissionError:
print(f"No permission to access {path}")
except NotADirectoryError as e:
print(e)
except Exception as e:
print(f"Unexpected error: {e}")
return False
Error Handling Workflow
graph TD
A[Start Directory Operation] --> B{Validate Path}
B -->|Valid Path| C{Check Permissions}
B -->|Invalid Path| D[Handle Path Error]
C -->|Permitted| E[Perform Operation]
C -->|Denied| F[Handle Permission Error]
E --> G[Return Success]
D --> H[Return Failure]
F --> H
Advanced Error Logging
import logging
from pathlib import Path
## Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s: %(message)s'
)
def robust_directory_handler(path):
try:
directory = Path(path)
if not directory.exists():
logging.warning(f"Directory not found: {path}")
directory.mkdir(parents=True)
logging.info(f"Created missing directory: {path}")
## Additional operations
except PermissionError:
logging.error(f"Permission denied for directory: {path}")
except Exception as e:
logging.critical(f"Unexpected error: {e}")
Best Practices
- Use specific exception types
- Provide informative error messages
- Log errors for debugging
- Implement fallback mechanisms
- Avoid silent failures
LabEx Recommendation
In LabEx's Python development environments, always implement comprehensive error handling to create robust and reliable scripts.
Key Takeaways
- Understand different directory-related exceptions
- Use try-except blocks strategically
- Log errors for better debugging
- Handle permissions and path validations
- Create resilient code that gracefully manages unexpected scenarios