Search code examples
javasonarqubetry-with-resources

sonarqube: Is try-with-resources or close this "ObjectInputStream" in a "finally" clause for this code false positive?


For the below java code though resource is closed in a finally block sonar is reporting:Use try-with-resources or close this “ObjectInputStream” in a “finally” clause.

FileInputStream fileInputStream = null;
ObjectInputStream objIn = null;
try {
    fileInputStream = new FileInputStream(value);
    objIn = new ObjectInputStream(fileInputStream)
}
finally {
        try 
            {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (objIn != null) {
                objIn.close();
            }
        } catch (IOException e) {}
    }

Sonar doesn't report above issue when try-with-resources is used , since the version of java i use doesn't support try-with-resource i had to go with closing resource in a finally block.


Solution

  • It is not a false positive.

    If fileInputStream.close() throws an exception, objIn.close() will not be called and the ObjectInputStream will not be closed.

    You should separate the two close calls to make sure both streams are closed:

    finally {
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException ignored) {}
    
        try {
            if (objIn != null) {
                objIn.close();
            }
        } catch (IOException ignored) {}
    }