Quantcast
Viewing all articles
Browse latest Browse all 39

Nested Try Block Statement : Exception Handling in Java

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 this example 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 code each and every exception is handled. In order to handle each exception we need to use try block.

The post Nested Try Block Statement : Exception Handling in Java appeared first on Learn Java Programming.


Viewing all articles
Browse latest Browse all 39

Trending Articles