Error Handling
Common Conversion Errors
Identifying Potential Exceptions
## Common error scenarios
try:
float("hello") ## ValueError
float(None) ## TypeError
except ValueError as ve:
print("Invalid string conversion")
except TypeError as te:
print("Unsupported type conversion")
Error Handling Strategies
Comprehensive Error Management
def safe_float_conversion(value, default=0.0):
try:
return float(value)
except (ValueError, TypeError):
print(f"Conversion failed for {value}")
return default
Error Handling Workflow
graph TD
A[Input Value] --> B{Conversion Attempt}
B --> |Success| C[Return Float]
B --> |Failure| D{Error Type}
D --> |ValueError| E[Handle String Error]
D --> |TypeError| F[Handle Type Error]
E --> G[Return Default Value]
F --> G
Error Types and Handling
Error Type |
Description |
Handling Strategy |
ValueError |
Invalid string conversion |
Provide default value |
TypeError |
Unsupported type |
Return predefined default |
Overflow |
Number too large |
Catch and manage |
Advanced Error Handling Techniques
Logging and Reporting
import logging
def robust_float_conversion(value):
try:
return float(value)
except ValueError:
logging.warning(f"Invalid float conversion: {value}")
return None
except TypeError:
logging.error(f"Unsupported type for conversion: {type(value)}")
return None
## LabEx recommended logging approach
logging.basicConfig(level=logging.WARNING)
Practical Error Handling Examples
def handle_mixed_inputs(inputs):
converted_values = []
for item in inputs:
try:
converted_values.append(float(item))
except (ValueError, TypeError):
print(f"Skipping invalid input: {item}")
return converted_values
## Example usage
mixed_inputs = [1, "2.5", "invalid", 3.14, None]
result = handle_mixed_inputs(mixed_inputs)
print(result) ## Output: [1.0, 2.5, 3.14]
Best Practices
- Always use try-except blocks
- Provide meaningful error messages
- Use logging for tracking conversion issues
- Implement default value strategies
- Validate inputs before conversion
Key Takeaways
- Error handling prevents program crashes
- Multiple error types require specific strategies
- Logging helps in debugging and monitoring
- Default values ensure continuous program execution