Returning value from catch/finally in java?

exception, java, jdbc

Solution

It won't work as you've written it. To execute the return with the `finally` block properly, you need to keep state, i.e.

boolean result = false;

try
{
 // all good
 result = true;
} 
catch(...)
{
 // crap
 result = false;
}
finally
{
 // close
}
return result;

This assumes that you want what's in the `finally` block to be executed and the correct result to be returned.

Problem

I have below code. if query is executed without exception then true should return, if any exception is thrown then false should be returned. and finally statement and connection should be closed. my question is where should i write return statement? in catch or finally? in below code i am returning true in try if query is executed, and false in catch if any exception is thrown. my question is if any exception is thrown, does returning false and closing connection and statement happens? ``` try { statement = connection.createStatement(); statement.executeQuery("select * from dual"); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } finally{ try { statement.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ```

Original source