Path: csiph.com!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 06:49:43 +0200 Organization: Decebal Computing Lines: 62 Message-ID: <87a839wdjs.fsf@munus.decebal.nl> References: <87poc6wb9n.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="12067"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19RuzH/86cybevg9QUUvDFfjDmSJRhdUfY=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux) Cancel-Lock: sha1:mYRAUIu1u2QfQtxJiQCcSg471yk= sha1:q9fiTPdq6fJh+1Rg70NDaybkcLo= X-Homepage: http://www.decebal.nl/ Xref: csiph.com comp.lang.java.programmer:37097 Patrick Roemer writes: > Responding to Stefan Ram: >> Cecil Westerhof writes: >>>It feels a bit long-winded. >> >> Yes. The method is too long. We need to refactor. > > Up to here we agree. ;) > > I'd rather move towards something like this: > > > private static void statistics(Connection conn) { > try (Statement stmt = conn.createStatement()) { > String format = runQueryFun(stmt, COUNT_TOTAL_PROV, > rs -> totalStats(rs.getInt("no"))); > runQueryProc(stmt, COUNT_UNUSED_PROV, > rs -> unusedStats(format, rs.getInt("no"))); > runQueryProc(stmt, COUNT_USED_PROV, > rs -> usedStats(format, rs.getInt("no"))); > } > catch (SQLException e) { > System.err.printf("Error in statistics\n"); > e.printStackTrace(); > fatalError(""); // wat?! > } > } > Does not completely what I did, but I found a solution that does something like this. See my reply on my own post. It is just a desktop application. So I have a method fatalError which prints an error if necessary and ‘cleanly’ exists the application. private static void fatalError(String message) { if (!message.equals("")) { System.err.println(message); } deinit(1); } And the deinit method: private static void deinit(int exitCode) { if (conn != null) { try { conn.close(); } catch (SQLException e) { System.err.printf("deinit: Could not close the connection\n"); } conn = null; } System.exit(exitCode); } I know that in principle the connection does not need to be closed, but I prefer to do it. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof