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

Nested try catch block example in Java

Filed under: Java on 2023-09-19 06:47:47

//  Program to explain Nested Try-Catch Block.

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


Output:

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

 Divide by 0: java.lang.ArithmeticException: / by zero  


 case (2) if we pass one arguments in commandline

 a = 1
 Divide by 0: java.lang.ArithmeticException: / by zero  


 case (3) if we pass two arguments in commandline

 a = 2
 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException: 10

About Author:
S
Shyam Dubey     View Profile
If you are good in any field. Just share your knowledge with others.