Effective Error Handling
Error Handling Strategies
graph TD
A[Error Handling] --> B[Try-Except Blocks]
A --> C[Custom Error Management]
A --> D[Logging and Reporting]
Basic Error Handling Techniques
Technique |
Purpose |
Example |
try-except |
Catch specific errors |
Prevent program crash |
else clause |
Execute code if no error |
Additional processing |
finally clause |
Always execute code |
Resource cleanup |
Comprehensive Error Handling Example
def advanced_error_handling():
def convert_data(value):
try:
## Attempt multiple conversions
if isinstance(value, str):
return int(value)
elif isinstance(value, float):
return str(value)
else:
raise ValueError("Unsupported conversion")
except ValueError as ve:
print(f"Conversion Error: {ve}")
return None
except TypeError as te:
print(f"Type Error: {te}")
return None
else:
print("Conversion successful")
return value
finally:
print("Conversion process completed")
## Test different scenarios
test_values = [42, "123", 3.14, "hello"]
for item in test_values:
result = convert_data(item)
print(f"Input: {item}, Result: {result}\n")
## Execute error handling demonstration
advanced_error_handling()
Advanced Error Management
Custom Exception Handling
class ConversionError(Exception):
"""Custom exception for conversion failures"""
def __init__(self, value, message="Conversion failed"):
self.value = value
self.message = f"{message}: {value}"
super().__init__(self.message)
def safe_conversion(value):
try:
## Simulate complex conversion with custom error
if not str(value).isdigit():
raise ConversionError(value)
return int(value)
except ConversionError as ce:
print(f"Custom Error: {ce.message}")
return None
## Demonstrate custom error handling
results = [safe_conversion(x) for x in ["100", "abc", 42, "250"]]
print("Conversion Results:", results)
Best Practices
- Use specific exception types
- Provide meaningful error messages
- Log errors for debugging
- Implement graceful error recovery
At LabEx, we recommend comprehensive error handling to create robust Python applications.