Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Cecil Westerhof Newsgroups: comp.lang.java.programmer Subject: Re: Is this the way to work with try with resources Date: Wed, 09 Aug 2017 22:20:28 +0200 Organization: Decebal Computing Lines: 42 Message-ID: <87tw1gtrw3.fsf@munus.decebal.nl> References: <87poc6wb9n.fsf@munus.decebal.nl> <87lgmtwels.fsf@munus.decebal.nl> <8760dxuhzl.fsf@munus.decebal.nl> <87y3qstzey.fsf@munus.decebal.nl> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Info: mx02.eternal-september.org; posting-host="75662a87a83d79e99d1b79ff65a19ab5"; logging-data="20878"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+zIT3xwc8xBBIXqwesmJ7tC5+MT+IHz1Y=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux) Cancel-Lock: sha1:Ridn578Pa45m8WSr/rSU25VMn3U= sha1:bCe+hW8wFl7FHQi8sKIoun6RMyI= X-Homepage: http://www.decebal.nl/ Xref: csiph.com comp.lang.java.programmer:37116 Andreas Leitgeb writes: > Cecil Westerhof wrote: >> I had there the following function: >> public ResultSet executeQuery(String query) throws SQLException { >> return conn.createStatement().executeQuery(query); >> } >> but I now changed that to: >> public ResultSet executeQuery(String query) throws SQLException { >> try (Statement stmt = conn.createStatement()) { >> return stmt.executeQuery(query); >> } >> } >> This should take care of the leakage. > > I fear, next trouble is right ahead. > > try doesn't only close it's resource on failure, but also on completion! > > That means, it will (because closing the statement will also close the > ResultSet) return an already closed ResultSet. I have in my code: private static void displayOldestUsed() { try (ResultSet rsOldest = sqlite3Conn.executeQuery(OLDEST_USED)) { if (rsOldest.next()) { giveMessage("Oldest used: " + rsOldest.getString("used") + "."); } } catch (SQLException e) { giveError("Error in displayOldestUsed"); e.printStackTrace(); fatalError(""); } } And rsOldest.getString("used") gives the result I would expect. Or am I just ‘lucky’? -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof