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.

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.

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.

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: