2

Should I initialize Statement and ResultSet in try-with-resources Statement or just initialize in try block and close Statement and ResultSet in finally block.

I need to understand the best way to implement this according to the best practices

try-with-resources Statement

try(Connection connection = DriverManager.getConnection("url");
    Statement st = connection.createStatement();
    ResultSet rs = st.executeQuery("query")){

} catch (SQLException e) {
    e.printStackTrace();
}

or try-catch with finally

Statement st = null;
        ResultSet rs = null;
        try(Connection connection = DriverManager.getConnection("url"))
        {
            st = connection.createStatement();
            rs = st.executeQuery("query");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Roshanck
  • 2,220
  • 8
  • 41
  • 56
  • [How should I use try-with-resources with JDBC?](http://stackoverflow.com/questions/8066501/how-should-i-use-try-with-resources-with-jdbc) has more discussion on best practises. – Mick Mnemonic Aug 22 '15 at 21:47

1 Answers1

2

I believe that most of the time less code is more clean code.Secondly readability does matter if you are working with a team and your team member can not read your code properly than it's definitely your fault.

In first case its look quite simple and easily understandable for the programmer who have worked with Java7 and removes the boiler plate code of closing the resources.In the second case you first initialized with null and have finally block with try-close-catch session.It is always better to go with the clean code which is the first one and note one more thing,

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Problem with try-with-resource is you can not use the resources out of the scope of try it will be limited to try block while that's not the case in your second part.

akash
  • 22,664
  • 11
  • 59
  • 87