Java Nested Try Block



Sometimes situation occurred, where we need to catch multiple conditions. In the previous tutorial we have learnt about the catching multiple exception using only one catch block. In this chapter we will be learning nested try block. Consider the following snippet –

public class ExceptionExample {

    public static void main(String argv[]) {

     int result = 0;
     int arr[] = new int[5];

     arr[5] = 5;

     result = 100 / 0;
     System.out.println("Result of Division : " + result);

  }
}

In the above example of nested try block we can see that

arr[5] = 5;
result = 100 / 0;

both these lines will generate exception.If we put both these codes in same try block then it will generate one exception and the next code won’t be executed.

public class ExceptionExample {

    public static void main(String argv[]) {

     int num1 = 10;
     int num2 = 0;
     int result = 0;
     int arr[] = new int[5];

	try {
	     try {
	     arr[5] = 5;
	}catch (ArrayIndexOutOfBoundsException e) {
	System.out.println("Err: Array Out of Bound");
	}    

	try {
	     result = num1 / num2;
	}catch (ArithmeticException e) {
	     System.out.println("Err: Divided by Zero");
	}
	System.out.println("Result of Division : " + result);

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

  }
}

In the above nested try block code each and every exception is handled. In order to handle each exception we need to use try block.