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