Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Martin Gregorie Newsgroups: comp.lang.java.programmer Subject: Re: Eclipse doesn't like else Date: Fri, 12 May 2017 21:22:01 -0000 (UTC) Organization: A noiseless patient Spider Lines: 74 Message-ID: References: <3c792901-a05d-4a02-b058-20b9e0576095@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Injection-Date: Fri, 12 May 2017 21:22:01 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="4f1ea27fc474fb47d73473d3d67e11ad"; logging-data="13895"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/9WdkwGg9K1NHVYlrybic8AqJfdv7hKeI=" User-Agent: Pan/0.141 (Tarzan's Death; 168b179 git.gnome.org/pan2) Cancel-Lock: sha1:ZCBghOj6KR7RXhVOcARltKAOhoc= Xref: csiph.com comp.lang.java.programmer:36611 On Fri, 12 May 2017 10:44:34 -0700, 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. I'd probably pull the repeated JDBC statements out into a separate method, something like: private void doQuery(String query) throws SQLException { try { PreparedStatement myPrep; myPrep = conn.prepareStatement(query); myPrep.executeQuery(); myPrep.close(); } catch (SQLException e) { /* Deal with anything handleable at point before re-throwing the query */ throw e; } } and then call it three times, though doubtless in RealLife(TM) it would need to be a bit more complex because your example code doesn't show what is done with the query's results. Similarly, the method's catch block may be unnecessary if it cant add value by by being there. -- martin@ | Martin Gregorie gregorie. | Essex, UK org |