Error Handling Strategies
Error handling is critical when working with integer inputs to prevent program crashes and provide a smooth user experience.
Common Exception Types
graph TD
A[Integer Input Exceptions] --> B[NumberFormatException]
A --> C[InputMismatchException]
A --> D[ArithmeticException]
Basic Exception Handling Techniques
1. Try-Catch Block Approach
import java.util.Scanner;
import java.util.InputMismatchException;
public class BasicExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int userInput = scanner.nextInt();
System.out.println("You entered: " + userInput);
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid integer.");
} finally {
scanner.close();
}
}
}
2. Multiple Exception Handling
public class MultiExceptionHandling {
public static void processInteger(String input) {
try {
int number = Integer.parseInt(input);
int result = 100 / number; // Potential divide by zero
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid number format");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} catch (Exception e) {
System.out.println("An unexpected error occurred");
}
}
public static void main(String[] args) {
String[] inputs = {"10", "0", "abc", "20"};
for (String input : inputs) {
processInteger(input);
}
}
}
Exception Handling Strategies
Strategy |
Description |
Best Used When |
Try-Catch |
Handle specific exceptions |
Known potential errors |
Throw |
Propagate errors to caller |
Complex error scenarios |
Custom Exceptions |
Create specific error types |
Domain-specific validations |
Advanced Error Handling Pattern
public class RobustInputHandler {
public static Optional<Integer> safeParseInteger(String input) {
try {
int parsedValue = Integer.parseInt(input);
return Optional.of(parsedValue);
} catch (NumberFormatException e) {
System.err.println("Invalid input: " + input);
return Optional.empty();
}
}
public static void main(String[] args) {
String[] testInputs = {"123", "abc", "456", "-789"};
for (String input : testInputs) {
safeParseInteger(input)
.ifPresentOrElse(
value -> System.out.println("Valid input: " + value),
() -> System.out.println("Skipping invalid input")
);
}
}
}
Logging and Error Reporting
import java.util.logging.Logger;
import java.util.logging.Level;
public class LoggingErrorHandler {
private static final Logger LOGGER = Logger.getLogger(LoggingErrorHandler.class.getName());
public static void logIntegerError(String input, Exception e) {
LOGGER.log(Level.WARNING, "Error processing input: " + input, e);
}
public static void main(String[] args) {
try {
int value = Integer.parseInt("not a number");
} catch (NumberFormatException e) {
logIntegerError("not a number", e);
}
}
}
LabEx Learning Recommendations
When practicing error handling in LabEx:
- Always anticipate potential input errors
- Provide clear, user-friendly error messages
- Use logging for tracking and debugging
- Implement comprehensive error handling strategies