Java Exception Handling Demos
1. Handle ArithmeticException (Divide by Zero)
// File: [Link]
import [Link];
public class DivideByZeroDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter dividend: ");
int dividend = [Link]();
[Link]("Enter divisor: ");
int divisor = [Link]();
int result = dividend / divisor; // may throw ArithmeticException
[Link]("Result = " + result);
} catch (ArithmeticException ex) {
[Link]("■■ Cannot divide by zero. Details: " + ex);
} finally {
[Link]();
[Link]("Program finished safely.");
}
}
}
Sample Run:
Enter dividend: 12
Enter divisor: 0
■■ Cannot divide by zero. Details: [Link]: / by zero
Program finished safely.
2. Handle ArrayIndexOutOfBoundsException
// File: [Link]
public class ArrayIndexDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
try {
// Deliberately access an invalid index
[Link]("Element at index 10 = " + numbers[10]);
} catch (ArrayIndexOutOfBoundsException ex) {
[Link]("■■ Invalid array index. Details: " + ex);
}
[Link]("Program continues after handling the exception.");
}
}
Sample Run:
■■ Invalid array index. Details: [Link]: Index 10 out of bounds for len
Program continues after handling the exception.