Exception Handling
1. Basic Try-Catch:
public class BasicExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.err.println("An ArithmeticException occurred: " + e.getMessage());
}
}
}2. Multiple Catch Blocks:
public class MultipleCatchBlocks {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int result = numbers[4]; // This will throw an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("An ArrayIndexOutOfBoundsException occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("A general exception occurred: " + e.getMessage());
}
}
}3. Finally Block:
4. Custom Exception:
5. Rethrowing an Exception:

Last updated