You must close the resources in the reverse order that you opened (as if these resources are on the stack).
In Java 7, try-with-resources is the ideal way:
try ( Connection conn = somethingThatGetsAConnection(); Statement st = conn.createStatement(); Resultset rs = st.executeQuery("SELECT something"); ) { // Do stuff } catch (SQLException e) { // Do stuff }
And Java will take care of this for you, and it will close the resource in reverse order. See also Oracle trial resource tutorial :
Note that the methods of "closing" resources are called in the opposite order of their creation.
You can find a more detailed look at try-with-resources in Better Resource Management with Java SE 7: Beyond Syntactic Sugar
The Java language specification for Java 7 is mentioned in section 14.20.3 :
Resources are initialized in order from left to right. If the resource is not initialized (that is, its initializer expression throws an exception), then all resources initialized so far with the try -with-resources operator are closed. If all resources are initialized successfully, the try block executes as usual, and then all non-zero resources of the try -with-resources try are closed.
Resources are closed in the reverse order from the one in which they were initialized. A resource is closed only if it is initialized with a value other than zero. Exclusion from the closure of one resource does not prevent the closure of other resources.
This can also be seen as a clear indication that Java developers are considering closing resources in the reverse order, where they highlight the norm.
source share