import java.io.*;
public class ExceptionHandling {
// Basic try-catch
public static void basicTryCatch() {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Division by zero: " + e.getMessage());
}
}
// Multiple catch blocks
public static void multipleCatch() {
try {
// Some code
} catch (NullPointerException e) {
System.out.println("Null pointer: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Illegal argument: " + e.getMessage());
} catch (Exception e) {
System.out.println("General exception: " + e.getMessage());
}
}
// Try-catch-finally
public static void tryFinally() {
try {
// Code that might throw exception
} catch (Exception e) {
// Handle exception
} finally {
// Always executed
System.out.println("Cleanup code");
}
}
// Try-with-resources
public static void tryWithResources() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
// Resource automatically closed
}
}
// Custom exception
public static class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// Throwing exceptions
public static void throwException() throws CustomException {
throw new CustomException("Something went wrong");
}
// Exception propagation
public static void propagateException() throws IOException {
// Method declares it may throw IOException
}
}