• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2244
  • Last Modified:

Return statement and try/catch block


If I have a try/catch/finally block, and the return statement is INSIDE try block, will 'finally' be executed even if no exception is thrown?

try {
  // statements
  return y;
}
catch (Exception e) {
  // statements
}
finally {
  // statements to close database connections
}
0
rakhare
Asked:
rakhare
1 Solution
 
CEHJCommented:
Yes - finally always executed
0
 
rakhareAuthor Commented:

Will it be executed just before the return statement, or after?
0
 
CEHJCommented:
Before
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
rakhareAuthor Commented:
Thanks.
0
 
CEHJCommented:
:-)
0
 
aozarovCommented:
Just to make it clear...
The finally logic will be executed after the evaluation of the return statement (Java remembers what was returned and as long as the finally will not mask that return value [or even exception] that value
will be returned at the end of that method).
Consider this example (to get the idea):

public class C
{
      public static void main(String st[])
      {
            C c = new C();
            System.out.println(c.printValue());
      }

      int printValue()
      {
            int x = 10;

            try
            {
                  return x;
            }
            finally
            {
                  x++;

                  // try also this (bad habit but just to get the idea)
                  //return x;
            }
      }
}
0
 
limaidealCommented:
YES.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now