Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to handle multiple Exception with General Exception .

Java Code Example — Exception Handling Programs

ADVERTISEMENT

Java Program to handle multiple Exception with General Exception .

Objective

Write a Java program to handle any potential exception using the general Exception superclass.

Algorithm / Approach

  1. Use the same risky method that can throw either an ArithmeticException or an ArrayIndexOutOfBoundsException.
  2. Wrap the method call in a try block.
  3. Instead of writing specific catch blocks, write a single catch (Exception e) block.
  4. Print a generic error message like "Invalid data Input".
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(Exception e) {
   System.out.println("Invalid data Input");
  }
 }
}

Expected Output

Enter Num1: 5
Enter Num2: 0
Invalid data Input

Explanation of the Program

  • The Exception class is the parent superclass of all exceptions in Java.
  • Because of polymorphism, a catch (Exception e) block acts as a universal safety net. It can catch an ArithmeticException, a NullPointerException, or literally any other exception.
  • While this is highly convenient, it is generally considered a bad practice to ONLY catch the general Exception in large applications, because you lose the ability to handle different errors in specific ways.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT