Exception Handling Strategies
Understanding Number Parsing Exceptions
Common Exception Types in Number Parsing
public class NumberParsingExceptionDemo {
public static void main(String[] args) {
String[] inputs = {"123", "abc", "1.23", "1,000", null};
for (String input : inputs) {
try {
int parsedNumber = parseNumberSafely(input);
System.out.println("Parsed: " + parsedNumber);
} catch (NumberFormatException e) {
System.out.println("Format Error: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Null Input Error: " + e.getMessage());
}
}
}
private static int parseNumberSafely(String input) {
if (input == null) {
throw new NullPointerException("Input cannot be null");
}
return Integer.parseInt(input);
}
}
Exception Handling Strategies Matrix
Strategy |
Approach |
Pros |
Cons |
Try-Catch |
Handle specific exceptions |
Precise error management |
Verbose code |
Optional |
Wrap result in Optional |
Type-safe |
Additional overhead |
Default Values |
Return predefined value |
Simple implementation |
Potential silent errors |
Custom Validation |
Pre-parsing checks |
Proactive error prevention |
More complex logic |
Exception Handling Flowchart
graph TD
A[Number Parsing Input] --> B{Input Validation}
B -->|Invalid| C[Throw/Handle Exception]
B -->|Valid| D[Attempt Parsing]
D --> E{Parsing Successful?}
E -->|Yes| F[Return Parsed Number]
E -->|No| G[Exception Handling]
Advanced Exception Handling Techniques
Comprehensive Error Management
public class RobustNumberParser {
public static Optional<Integer> parseNumber(String input) {
try {
// Trim and validate input
if (input == null || input.trim().isEmpty()) {
return Optional.empty();
}
// Attempt parsing with additional checks
int parsedNumber = Integer.parseInt(input.trim());
return Optional.of(parsedNumber);
} catch (NumberFormatException e) {
// Log detailed error information
System.err.println("Parsing error: " + e.getMessage());
return Optional.empty();
}
}
public static void main(String[] args) {
Optional<Integer> result = parseNumber("123");
result.ifPresentOrElse(
num -> System.out.println("Parsed number: " + num),
() -> System.out.println("Parsing failed")
);
}
}
Logging and Monitoring Strategies
Implementing Comprehensive Error Tracking
import java.util.logging.Logger;
import java.util.logging.Level;
public class NumberParsingLogger {
private static final Logger LOGGER = Logger.getLogger(NumberParsingLogger.class.getName());
public static int parseWithLogging(String input) {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
LOGGER.log(Level.WARNING, "Number parsing failed for input: " + input, e);
throw e; // Re-throw or handle as needed
}
}
}
Best Practices for LabEx Developers
- Always validate input before parsing
- Use specific exception handling
- Implement logging mechanisms
- Provide meaningful error messages
- Consider using Optional for safer returns
By mastering these exception handling strategies, developers can create more resilient and predictable number parsing solutions in Java applications.