Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to handle multiple exception .

Java Code Example — Exception Handling Programs

ADVERTISEMENT

Java Program to handle multiple exception .

Objective

Write a Java program to handle multiple specific exceptions using separate catch blocks.

Algorithm / Approach

  1. Create a method that first performs division (x / y), and then uses that result as an index to access an array (a[z]).
  2. In main, wrap the method call in a try block.
  3. Write a catch (ArithmeticException e) block to handle division by zero.
  4. Write a second catch (ArrayIndexOutOfBoundsException e) block to handle cases where the division result is larger than the array size.
  5. 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, an ArithmeticException is thrown. If the user enters inputs that result in z = 10, an ArrayIndexOutOfBoundsException is thrown because the array only has 5 elements.
  • Java allows multiple catch blocks attached to a single try block. 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)
ADVERTISEMENT