Nested try block Overview

The try block can be nested.It means, One try block of statement in another try block.

Example of Nested try Block
class NestedTry { public static void main(String str[]) { try { int a= Integer.parseInt(str[0]); int b= Integer.parseInt(str[1]); try { int c= a/b; System.out.println("Result is :"+c); } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } catch(ArrayIndexOutOfBoundsException e1) { System.out.println("Divide by 0: " + e1); } finally { System.out.println("Finally Block executed"); } } }

Outer try block throws exception and handle by outer catch clause.


C:\JavaProgram\Exception\nestedTry>java NestedTry
Divide by 0: java.lang.ArrayIndexOutOfBoundsException: 0
Finally Block executed

Inner try block code throws the exception and handle by inner catch caluse and afterwards finally block will be executed.

C:\JavaProgram\Exception\nestedTry>java NestedTry 10 0
Divide by 0: java.lang.ArithmeticException: / by zero
Finally Block executed

Download this example


Latest Tutorial

Most Visited Tutorial