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();
}
}
It won’t work as you’ve written it. To execute the return with the
finallyblock properly, you need to keep state, i.e.This assumes that you want what’s in the
finallyblock to be executed and the correct result to be returned.