Wednesday, 24 April 2013

Java interview questions and answers: - We have return in the try block, will finally block execute?


Let us first try to understand this Java interview question. You can see below is a simple Java code which where in we have put a return statement in the try block. So the question is will finally block execute.


public static void main(String[] args)
      {
            try
            {
                  int i=0;
                  return;
            }
            finally
            {
                  // will the control come here
                  int z=0;
            }
           
      }


The answer is Yes Finally block will execute irrespective there is return or there are no return statements. That’s why finally block is the best place to put clean up code.


4 comments: