Tuesday, 19 May 2015

Nested try statements in Java exception handling

A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement.

Here note that you don’t have to have the whole try-catch-finally block it can be a try and catch or finally block.

In case a try-catch block can not handle the exception thrown the exception goes up the hierarchy (next try-catch block in the stack) and the next try statement's catch block handlers are inspected for a match. If no catch block, with in the hierarchy, handles the thrown exception then the Java run-time system will handle the exception.

Example code

public class NestedTryDemo {
    public static void main(String[] args) {
        try{
            System.out.println("In Outer try block");
            try{
                System.out.println("In Inner try block");
                int a = 7 / 0;
            }catch (IllegalArgumentException e) {
                System.out.println("IllegalArgumentException caught");
            }finally{
                System.out.println("In Inner finally");
            }
        }catch (ArithmeticException e) {
            System.out.println("ArithmeticException caught");
        }finally {
            System.out.println("In Outer finally");
        }
    }
}

Output

In Outer try block
In Inner try block
In Inner finally
ArithmeticException caught
In Outer finally

In this example, one try catch finally sequence has been nested within another try catch finally sequence. The inner try block throws an ArithmeticException which it could not handle, as the inner catch block catches IllegalArgumentException. Hence, this exception moves up the hierarchy and handled in the outer try-catch-finally block.

Better way to use nested try statement

In the above example you have seen how exception propagates and can be handled by the inner or outer block based on which catch block can handle it. But the better way to design nested try statements is to look for the code sections which are more likely to throw any specific exception and wrap those specific blocks in a try-catch block that can handle that exception and overall code can be wrapped in more general try-catch block.

Example code

Let’s change the above code a little bit, now there is a method with an int as argument. That argument is used to divide 7 in the code. Now you have a condition that passed argument should be less than or equal to 7 otherwise IllegalArgumentException must be thrown.

Also you need to check for divide by zero condition in which case you must handle ArithmeticException. Overall you may have a try-catch block which can handle any other exception.

To handle this scenario you may start a try block in which you can check if the passed value is less than or equal to 7 or not, if not throw IllegalArgumentException and then have a nested try-catch where you can handle ArithmeticException. After that you can have a catch block for the outer try to handle IllegalArgumentException.

public class NestedTryDemo {
    public static void main(String[] args) {
 NestedTryDemo nd = new NestedTryDemo();
 nd.process(8);
    }
 
    private void process(int num){
 try{
     try{
  if(num > 7){
      throw new IllegalArgumentException("Number should not 
                         be greater than 7");
  }
   
  try{
      System.out.println("In Inner try block");
      int a = 7 / num;
      System.out.println("value of a " + a);
  }catch (ArithmeticException e) {
      System.out.println("ArithmeticException caught - " + e.getMessage());
  }
     }catch(IllegalArgumentException e){
  System.out.println("IllegalArgumentException caught - " + e.getMessage());
     }
  
 }catch(Exception exp){
     System.out.println("Exception in the code " + exp.getMessage());
 }finally {
     System.out.println("In Outer finally");
 }
   }
}

Output

IllegalArgumentException caught - Number should not be greater than 7
In Outer finally

If you execute the same code by passing 0, then the output will be -

In Inner try block
ArithmeticException caught - / by zero
In Outer finally

If you execute the same code by passing 3, then the output will be

In Inner try block
value of a 2
In Outer finally

That's all for this topic Nested try statements in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. final Vs finally Vs finalize
  2. Difference between Checked exception & Unchecked exception
  3. Difference between throw and throws
  4. How to create a custom exception class
  5. try-with-resources in Java 7
  6. Java Exception Handling interview questions

You may also like -

1 comment: