Introduction

Another new feature in Java 7 is the try-with-resource statement. To explain it, lets first have a look at how we would implement a simple database query using JDBC, while making sure that all resources are properly closed independent of whether an exception is thrown by some of the methods or not. This example uses the scott/tiger sample database delivered with each Oracle database installation:

private void oldApproach() throws SQLException {
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // Remember: con.close(); !!
        stmt = con.createStatement();                                    // Remember: stmt.close(); !!
        rs = stmt.executeQuery("SELECT deptno, dname FROM dept");        // Remember: rs.close(); !!
        while(rs.next()) {
            System.out.println(rs.getString("deptno") + ": " + rs.getString("dname"));
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

This example shows that a lot of boilerplate code is necessary, especially to make sure that the resources are properly cleaned up. Note that, in this particular example, it might be sufficient to close the Connection object to release all dependant resources like Statements and ResultSets. Anyway, the example closes them all separately, mainly to make the difference to the code shown below even more obvious. Suppose you want to write the results into some file, then you need to take care of properly closing the output stream to the file in any case since it is independant from the JDBC connection.

Lets see how we can write the code with the new try-with-resources statement introduced in Java 7:

private void newApproach() throws SQLException {
    try (Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT deptno, dname FROM dept"))  {

        while(rs.next()) {
            System.out.println(rs.getString("deptno") + ": " + rs.getString("dname"));
        }
    }
}

Short, isn’t it? In this example, is is assured that the close() method is called on each of the objects declared within the parentheses of the try() – statement. The close methods are automatically called in reverse order as the references are declared in the try() – statement, and they are only called if they have been initialized, means if they are not null. This makes it much easier to write code which properly cleans up resources!

In the next section we will see how this actually works.