Search code examples
javatry-with-resourcesspotbugs

Is SpotBugs reporting a false positive on not closing a resource here?


I have code like this:

public static MyObject forId(long myObjectId, Connection cxn) throws SQLException {
    try (PreparedStatement stmt = cxn.prepareStatement(selectMyObjectById))) {
        stmt.setLong(1, myObjectId);
        try (ResultSet res = stmt.executeQuery()) {
            res.next();
            return MyObject.fromResultSet(res);
        }
    }
}

which SpotBugs identifies as OBL_UNSATISFIED_OBLIGATION for the JDBC Statement object. Is this a false positive? My impression is that try-with-resources will ensure these resources get closed properly in all cases.


Solution

  • Your ResultSet and PreparedStatement are protected as you rightly state.

    If your Connection is also appropriately handled in the relevant scope then yes, it is a false positive.