Exception Handling Techniques
Multiple Catch Blocks
Java allows handling multiple exceptions with different catch blocks:
public class MultiCatchDemo {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
}
}
}
Multi-Catch and Specific Exception Handling
graph TD
A[Try Block] --> B{Exception Occurs?}
B -->|Yes| C[Match Specific Catch Block]
B -->|No| D[Continue Execution]
C --> E[Handle Exception]
Exception Handling Strategies
| Strategy |
Description |
Use Case |
| Catch and Handle |
Directly manage the exception |
Recoverable errors |
| Throw and Declare |
Propagate exception to caller |
Complex error scenarios |
| Custom Exceptions |
Create domain-specific exceptions |
Specialized error handling |
Throwing Custom Exceptions
public class CustomExceptionDemo {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("Invalid age: " + age);
}
}
public static void main(String[] args) {
try {
validateAge(-5);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
Try-with-Resources
Automatic resource management for closeable resources:
public class ResourceHandlingDemo {
public static void main(String[] args) {
try (FileReader reader = new FileReader("example.txt")) {
// File processing
} catch (IOException e) {
System.out.println("File error: " + e.getMessage());
}
}
}
Advanced Exception Chaining
public class ExceptionChainingDemo {
public static void method() throws Exception {
try {
// Some operation
} catch (SQLException e) {
throw new Exception("Database error", e);
}
}
}
Best Practices
- Catch specific exceptions first
- Use finally for cleanup
- Log exceptions for debugging
- Avoid empty catch blocks
- Use meaningful error messages
Developers using LabEx can leverage these techniques to create robust and error-resistant Java applications.