Tutorials

Java Exception Handling


Nested try block


A block within a block is known as nested block.

 

try block inside a try block is known as nested try block

Syntax of nested try block

      try{

            //statement 1

            //statement 2

            try{

                  //statement 1

            }catch(ArithmeticException e){

            //statement 3    

      }catch(Exception e){
     
      }

Example: java nested try block


package exceptionHandling;

public class NestedTry {

      public static void main(String[] args) {

            try{

                  System.out.println("Nesed try begins");

                  try{

                        int a = 20, b = 0;

                        int div = a/b;

                  }catch(ArithmeticException e){

                        System.out.println("Division by 0 not allowed");

                  }


                  try{

                        int arr[] = {1,2,3,4,5};

                        System.out.println(arr[10]);

                  }catch(ArrayIndexOutOfBoundsException e){

                        System.out.println("index doesnot exists in array");

                  }

            }catch(Exception e){
                        System.out.println("Exception occured");
            }
      }
}

 

How nested try works?

 



Please Share this page
Views : 43