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

Multiple exceptions in single catch block example in Java

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

// Program to catch Multiple exceptions in single Catch Block.

class  Exception6
{
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 | ArrayIndexOutOfBoundsException e) 
 {
  System.out.println("Exception Caught: " + 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:
S
Shyam Dubey     View Profile
I am a good learner. I like posting new questions on this plateform to help other students.