Nested try block in java

In the previous post, we have seen try-catch block. In this post, we will discuss about the nested try block in java.

A try block placed inside another try block is known as Nested try block.

Suppose, a part of try block causes different error from the whole try block. In that case, we can use nested try block.

Syntax of Nested try block:

try  
{  
    statement 1;  
    statement 2;  
    try  
    {  
        statement 1;  
        statement 2;  
    }  
    catch(Exception e)  
    {  
    }  
}  
catch(Exception e)  
{  
}

Example of nested try :

public class TryCatchEx {
	
	static String name = null;
	public static void main(String[] args){	
		try{
	      int data=50/2;
	      System.out.println("Start a nested try");
	      try{
	    	  System.out.println(name.length());
	      }catch(NullPointerException n){
	    	  System.out.println("Error : variable is null");
	      }
	      int data1 = data/5;
	      System.out.println("data further divided after nested try block : "+data1);
		}catch(ArithmeticException e){
			System.out.println("Error : "+e.getMessage());
			System.out.println("Caught the error");
		}
	      System.out.println("Important steps to be executed");  // program will be executed
	}	
}
Output:
Start a nested try
Error : variable is null
data further divided after nested try block : 5
Important steps to be executed
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 9, 2015

    […] the previous post, we have seen Nested try blocks. In this post, we will see if it is possible to have multiple catch block or […]