• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2241
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

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