Java Program to handle multiple exception .
Objective
Write a Java program to handle multiple specific exceptions using separate catch blocks.
Algorithm / Approach
- Create a method that first performs division (
x / y), and then uses that result as an index to access an array (a[z]). - In main, wrap the method call in a
tryblock. - Write a
catch (ArithmeticException e)block to handle division by zero. - Write a second
catch (ArrayIndexOutOfBoundsException e)block to handle cases where the division result is larger than the array size. - Test the program with inputs that trigger both scenarios.
Test.java
import java.util.Scanner;
class Test {
public int find(int x, int y) {
int[] a = {1,2,3,4,5};
int z = x/y;
//May throw ArithmeticException
return a[z];
//may throw ArrayIndexOutOfBoundsException
}
}
class Main {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Num1: ");
int x = s.nextInt();
System.out.print("Enter Num2: ");
int y = s.nextInt();
Test t = new Test();
try {
int res = t.find(x,y);
System.out.println("Result = "+res);
}
catch(ArithmeticException e) {
System.out.println("Can't Divide by 0");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid Input");
}
}
}
Expected Output
Enter Num1: 4 Enter Num2: 0 Can't Divide by 0
Explanation of the Program
- A single block of code can potentially throw many different types of errors.
- In this program, if the user enters
y = 0, anArithmeticExceptionis thrown. If the user enters inputs that result inz = 10, anArrayIndexOutOfBoundsExceptionis thrown because the array only has 5 elements. - Java allows multiple
catchblocks attached to a singletryblock. The JVM will check them from top to bottom and execute the first one that matches the thrown exception.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)