Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sonarqube: Is try-with-resources or close this "ObjectInputStream" in a "finally" clause for below 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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) {}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading