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

388 views Asked by At

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.

2

There are 2 answers

5
rickdenhaan On BEST ANSWER

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) {}
}
0
SIMULATAN On

The finally is in the try when in reality it has to be outside.

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

Although I'm not sure if SonarQube will understand that you closed it.