Advanced Exception Techniques
Context Managers and Exception Handling
class FileHandler:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.close()
if exc_type is not None:
print(f"An exception occurred: {exc_type}")
return False
## Usage
with FileHandler('example.txt', 'w') as f:
f.write('LabEx exception handling example')
Exception Chaining
def complex_operation():
try:
## Some operation that might raise an exception
result = risky_function()
except ValueError as e:
raise RuntimeError("Complex operation failed") from e
Global Exception Handling
import sys
def global_exception_handler(exc_type, exc_value, exc_traceback):
print("Uncaught exception:")
print(f"Type: {exc_type}")
print(f"Value: {exc_value}")
sys.excepthook = global_exception_handler
Exception Handling Techniques
Technique |
Description |
Use Case |
Context Managers |
Manage resource allocation |
File, network, database operations |
Exception Chaining |
Link related exceptions |
Preserve original error context |
Global Exception Handlers |
Catch unhandled exceptions |
Logging, monitoring |
Decorators |
Wrap functions with error handling |
Consistent error management |
Decorator-based Error Handling
def error_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Error in {func.__name__}: {e}")
return wrapper
@error_handler
def divide_numbers(a, b):
return a / b
Exception Handling Flow
graph TD
A[Function Call] --> B{Try Block}
B -->|Exception| C[Specific Exception Handler]
B -->|No Exception| D[Normal Execution]
C --> E[Log Error]
C --> F[Raise/Handle Exception]
D --> G[Return Result]
Best Practices for Advanced Exception Handling
- Use specific exception types
- Implement comprehensive error logging
- Avoid catching generic exceptions
- Provide meaningful error messages
- Use context managers for resource management
At LabEx, we recommend mastering these advanced exception techniques to create more robust and maintainable Python applications.