Practical Error Prevention
Error Prevention Strategies
graph TD
A[Error Prevention] --> B[Input Validation]
A --> C[Defensive Programming]
A --> D[Proper Error Handling]
A --> E[Logging and Monitoring]
public class InputValidationDemo {
public static double divideNumbers(String num1, String num2) {
try {
// Validate numeric input
if (!isNumeric(num1) || !isNumeric(num2)) {
throw new IllegalArgumentException("Invalid numeric input");
}
double a = Double.parseDouble(num1);
double b = Double.parseDouble(num2);
// Prevent division by zero
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
} catch (NumberFormatException e) {
System.err.println("Conversion error: " + e.getMessage());
return 0.0;
}
}
private static boolean isNumeric(String str) {
return str != null && str.matches("-?\\d+(\\.\\d+)?");
}
public static void main(String[] args) {
System.out.println(divideNumbers("10", "2"));
System.out.println(divideNumbers("10", "0"));
System.out.println(divideNumbers("abc", "2"));
}
}
2. Defensive Programming Approaches
Safe Numeric Calculations
public class SafeCalculationDemo {
public static int safeAdd(int a, int b) {
// Check for potential overflow
if (b > 0 && a > Integer.MAX_VALUE - b) {
throw new ArithmeticException("Integer overflow");
}
if (b < 0 && a < Integer.MIN_VALUE - b) {
throw new ArithmeticException("Integer underflow");
}
return a + b;
}
public static void main(String[] args) {
try {
int result = safeAdd(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
System.err.println("Calculation error: " + e.getMessage());
}
}
}
3. Error Handling Best Practices
Practice |
Description |
Example |
Fail Fast |
Detect and handle errors early |
Validate inputs before processing |
Graceful Degradation |
Provide fallback mechanisms |
Return default values |
Comprehensive Logging |
Record detailed error information |
Use logging frameworks |
4. Advanced Error Prevention Techniques
import java.util.Optional;
public class OptionalHandlingDemo {
public static Optional<Double> safeDivide(double a, double b) {
// Use Optional to handle potential errors
return (b != 0)
? Optional.of(a / b)
: Optional.empty();
}
public static void main(String[] args) {
Optional<Double> result = safeDivide(10, 2);
result.ifPresentOrElse(
value -> System.out.println("Result: " + value),
() -> System.out.println("Division not possible")
);
}
}
5. Logging and Monitoring
import java.util.logging.Logger;
import java.util.logging.Level;
public class ErrorLoggingDemo {
private static final Logger LOGGER = Logger.getLogger(ErrorLoggingDemo.class.getName());
public static void processData(String input) {
try {
// Simulated data processing
if (input == null || input.isEmpty()) {
throw new IllegalArgumentException("Invalid input");
}
LOGGER.info("Processing input: " + input);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error processing data", e);
}
}
public static void main(String[] args) {
processData(null);
}
}
LabEx Insight
Mastering error prevention requires consistent practice. LabEx provides interactive environments to help you develop robust error-handling skills in real-world scenarios.