Practical Error Handling
Error Handling Strategies for Integer Division
1. Comprehensive Error Management
type DivisionError struct {
Dividend int
Divisor int
Message string
}
func (e *DivisionError) Error() string {
return fmt.Sprintf("division error: %s (dividend: %d, divisor: %d)",
e.Message, e.Dividend, e.Divisor)
}
2. Error Handling Workflow
graph TD
A[Input Validation] --> B{Division Possible?}
B -->|No| C[Generate Custom Error]
B -->|Yes| D[Perform Division]
D --> E[Return Result]
C --> F[Error Logging]
F --> G[Error Recovery/Notification]
3. Advanced Error Handling Techniques
Technique |
Description |
Implementation |
Custom Error Types |
Create specific error structures |
Implement Error() interface |
Contextual Errors |
Add context to errors |
Use fmt.Errorf() with %w |
Structured Logging |
Detailed error information |
Use logging frameworks |
Robust Division Function
func safeDivideWithContext(dividend, divisor int) (int, error) {
// Zero division check
if divisor == 0 {
return 0, &DivisionError{
Dividend: dividend,
Divisor: divisor,
Message: "cannot divide by zero",
}
}
// Overflow prevention
if dividend == math.MinInt64 && divisor == -1 {
return 0, &DivisionError{
Dividend: dividend,
Divisor: divisor,
Message: "integer overflow",
}
}
return dividend / divisor, nil
}
Error Handling Patterns
Error Wrapping and Context
func processCalculation(x, y int) error {
result, err := safeDivideWithContext(x, y)
if err != nil {
// Wrap error with additional context
return fmt.Errorf("calculation failed: %w", err)
}
log.Printf("Calculation result: %d", result)
return nil
}
LabEx Recommended Practices
- Always return errors explicitly
- Use custom error types for detailed information
- Implement comprehensive error logging
- Provide clear error messages
Logging and Monitoring
func handleDivisionError(err error) {
switch e := err.(type) {
case *DivisionError:
log.Printf("Division Error: %v", e)
// Implement specific error handling
default:
log.Printf("Unexpected error: %v", err)
}
}
Key Error Handling Principles
- Fail fast and explicitly
- Provide meaningful error information
- Use structured error handling
- Implement appropriate error recovery mechanisms