Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: v_borchert@despammed.com (Volker Borchert) Newsgroups: comp.lang.java.programmer Subject: Re: Eclipse doesn't like else Date: 13 May 2017 00:52:52 GMT Organization: Private site at Eddersheim, Germany Lines: 73 Distribution: world Message-ID: References: <3c792901-a05d-4a02-b058-20b9e0576095@googlegroups.com> X-Trace: individual.net yGnSJct4e6A5LKOKb8KcxQO/bgT2D8CUPyMvlanl/0j6BpSJ1e Cancel-Lock: sha1:xKXY/ySnhn+BblahO4jaWEU0qfc= Xref: csiph.com comp.lang.java.programmer:36612 Eric Douglas wrote: > Why must it give a warning on this else condition? > > import java.sql.Connection; > import java.sql.DriverManager; > import java.sql.PreparedStatement; > import java.sql.SQLException; > > public class CompileMe { > public static void testMe() { > try { > Connection conn = DriverManager.getConnection("db_connect_string", "db_userid", "db_password"); > String someCondition = "check me"; > PreparedStatement myPrep; > myPrep = conn.prepareStatement("initial query"); > myPrep.executeQuery(); > myPrep.close(); > if (someCondition.equals("one")) { > myPrep = conn.prepareStatement("query something"); > } else { > myPrep = conn.prepareStatement("query something else"); > } > myPrep.executeQuery(); > myPrep.close(); > } catch (SQLException e) { > e.printStackTrace(); > } > } > } > > This example will run the same whether we have 2 calls to prepareStatement, or set one common string to pass into prepareStatement after the if, but if we write it this way Eclipse gives a warning "Resource leak: 'myPrep' is not closed at this location". > > Take out the 3 lines above the if (prepare, execute, and close a different query) and the warning goes away. Now let's combine the suggestions (note: did not try to actually compile): import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class CompileMe { private static void query(final Connection conn, final String sql) throws SQLException { try (final PreparedStatement stmt = conn.prepareStatement(sql)) { try (final ResultSet rslt = stmt.executeQuery()) { // do something with result. // try-with-resources will take care of // close()ing the ResultSet when done. } } } public static void testMe() { try (final Connection conn = DriverManager.getConnection("db_connect_string", "db_userid", "db_password")) { String someCondition = "check me"; query(conn, "initial query"); if (someCondition.equals("one")) { query(conn, "query something"); } else { query(conn, "query something else"); } } catch (SQLException e) { e.printStackTrace(); } } } -- "I'm a doctor, not a mechanic." Dr Leonard McCoy "I'm a mechanic, not a doctor." Volker Borchert