Error Handling Patterns
Introduction to Error Handling
Error handling is a crucial aspect of robust Java programming, ensuring applications can gracefully manage unexpected situations and maintain system stability.
1. Try-Catch-Finally Pattern
public void processFile(String filename) {
try {
// File processing logic
FileReader reader = new FileReader(filename);
// Read file contents
} catch (FileNotFoundException e) {
// Handle specific file not found scenario
System.err.println("File not found: " + filename);
} catch (IOException e) {
// Handle general I/O errors
System.err.println("I/O error occurred");
} finally {
// Resource cleanup code
// Always executed, regardless of exception
}
}
2. Exception Hierarchy and Handling
graph TD
A[Throwable] --> B[Error]
A --> C[Exception]
C --> D[RuntimeException]
C --> E[Checked Exception]
Exception Types Comparison
Exception Type |
Characteristics |
Handling Requirement |
Checked Exception |
Must be declared or handled |
Compile-time check |
Unchecked Exception |
Optional handling |
Runtime check |
Error |
Serious system-level issues |
Typically not caught |
3. Custom Exception Creation
public class CustomValidationException extends RuntimeException {
public CustomValidationException(String message) {
super(message);
}
}
public class UserService {
public void validateUser(User user) {
if (user.getAge() < 18) {
throw new CustomValidationException("User must be 18 or older");
}
}
}
4. Logging and Error Tracking
import java.util.logging.Logger;
import java.util.logging.Level;
public class ErrorLogger {
private static final Logger LOGGER = Logger.getLogger(ErrorLogger.class.getName());
public void processData(String data) {
try {
// Process data
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error processing data", e);
}
}
}
5. Modern Error Handling Techniques
Optional Class
public Optional<User> findUserById(int id) {
return userRepository.findById(id)
.filter(user -> user.isActive())
.orElseThrow(() -> new UserNotFoundException("User not found"));
}
Error Handling Flow
graph TD
A[Method Execution] --> B{Exception Occurs?}
B -->|Yes| C[Catch Exception]
B -->|No| D[Continue Execution]
C --> E{Log Error}
E --> F{Handle/Recover}
F -->|Recover| G[Continue]
F -->|Cannot Recover| H[Throw/Propagate]
LabEx Recommendations
At LabEx, we emphasize:
- Precise exception handling
- Meaningful error messages
- Minimal performance overhead
Best Practices
- Use specific exceptions
- Avoid empty catch blocks
- Log errors with context
- Fail fast and explicitly
- Use try-with-resources for automatic resource management
Conclusion
Effective error handling is not just about catching exceptions, but creating resilient and maintainable code that provides clear feedback and maintains system integrity.