O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Rewrite the previous example using the new try-with-resources statement:
        void execute(Statement st, String sql){          try (st) {            st.execute(sql);          } catch (Exception ex) {            ex.printStackTrace();          }        }

As you can see, it is much more concise and focused, without the need of repeatedly writing trivial code that closes the resource. No more finally and extra try...catch in it.

  1. Try and write it so that it closes the connection as soon as it was used:
        void execute(Connection conn, Statement st, String sql) {          try (conn; st) {            st.execute(sql);          } catch (Exception ex) {            ex.printStackTrace();          }        }

It may or may not fit your application connection handling, but often, this capability is handy.

  1. Try a different combination, such as the following: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required