// Basic exception handling
try {
int[] numbers = {1, 2, 3};
int value = numbers[5]; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds: " + e.getMessage());
}
// Handling multiple exceptions
try {
String str = null;
int length = str.length(); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Null pointer exception");
} catch (Exception e) {
System.out.println("General exception: " + e.getMessage());
}
// Finally block
try {
// Risky operation
} catch (Exception e) {
// Handle exception
} finally {
// Always executed for cleanup
System.out.println("Cleanup");
}
// Try-with-resources (auto-closes)
try (FileInputStream fis = new FileInputStream("file.txt")) {
// Read from file
} catch (IOException e) {
System.out.println("IO error: " + e.getMessage());
}
// FileInputStream automatically closed
// Catching and rethrowing
try {
riskyOperation();
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
throw new RuntimeException("Wrapped exception", e);
}
// Checked exception handling
public void readFile() {
try {
FileReader reader = new FileReader("file.txt");
// Use reader
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO error: " + e.getMessage());
}
}