In code where I can rely on Java 7, I would probably use try-with-resources as suggested by Duncan Jones .
There are two approaches in my previous code that I used:
The first is a set of helper methods in a static helper class, in this form:
public static final Statement quietClose(Statement s) { if (s != null) { try { s.close(); } catch (Exception e) {
Then in the finally block:
stmt = Helper.quietClose(stmt);
The second approach was to use LinkedList , add things to it in the order that I opened them, and then have an assistant who would loop in the reverse order and basically do it.
In all cases, I try to keep the methods short enough so that in the end there are no 18 different JDBC objects that I need to close. (I say that I "aspire" ... I do not always succeed.)
source share