I was reviewing my own code and I found this in the finally clause of a db application:

} finally {
    try {
        if (res != null) res.close();
        if (stmt != null) stmt.close();
    } catch (SQLException ex) {
        throw ex;
    }
}

In other words if res.close() throws and exception, line 4 is not executed and so the statement doesn’t get closed! It’s quite subtle because finally statements are already annoying and by writing them in this way I didn’t see the problem. A better way to implement this is to write two close methods that actually ignore the error.

private static void close(ResultSet rs) {
    if (rs==null) return;
    try {
        rs.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
} 

private static void close(Statement sm) {
    if (sm==null) return;
    try {
        sm.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

So theĀ  finally clause now looks cleaner, shorter and actually works!

} finally {
    close(stmt);
    close(res);
}