Java Program to handle multiple exception in a single catch .
Objective
Write a Java program to handle multiple exceptions in a single catch block (Multi-catch).
Algorithm / Approach
- Use the same risky division and array access method.
- Wrap the method call in a
tryblock. - Write a single catch block using the pipe operator:
catch (ArithmeticException | ArrayIndexOutOfBoundsException e). - Inside the catch block, print the exception object
eto see exactly which error was triggered.
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 ArrayIndexOutOfBoundsExcep.
}
}
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 |
ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
}
}
Expected Output
Enter Num1: 20 Enter Num2: 2 java.lang.ArrayIndexOutOfBoundsException: 10
Explanation of the Program
- Before Java 7, if you wanted to handle two different exceptions with the exact same error-handling logic, you had to duplicate the code across two catch blocks.
- The Multi-catch feature allows you to catch multiple distinct exception types in a single block using the bitwise OR (pipe) operator
|. - This significantly reduces code duplication while maintaining strict, specific exception checking (unlike catching the general Exception superclass).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)