You are here: Home / Topics / Multiple catch block example in Java

Multiple catch block example in Java

Filed under: Java on 2023-09-19 06:45:13

// Program to use Multiple Catch Block with Exception.

class Exception05 
{
public static void main(String args[ ]) 
{
 try 
 {
  int a = args.length;
  System.out.println("a = " + a);
  int b = 10 / a;
  int c[ ] = { 1 };
  c[10] = 100;
 } 
 catch(ArithmeticException e) 
 {
  System.out.println("Divide by 0: " + e);
 } 
 catch(ArrayIndexOutOfBoundsException e) 
 {
  System.out.println("Array index oob: " + e);
 }
 System.out.println("After try/catch blocks.");
}
}


Output:

 case (1) if we don't pass any arguments in commandline

 a = 0
 Divide by 0: java.lang.ArithmeticException: / by zero
 After try/catch blocks.
 

 case (2) if we pass one arguments in commandline

 a = 1
 Array index oob:  java.lang.ArrayIndexOutOfBoundsException: 10
 After try/catch blocks.


About Author:
M
Mr. Dubey     View Profile
Founder of MCQ Buddy. I just like to help others. This portal helps students in getting study material free. Share your stuff here so that others can get benefitted.