Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant nullcheck of value known to be non-null or possible bug in findbugs

Tags:

java

findbugs

Here is the code:

public static String readFile(InputStream is) {

        try (Scanner scanner = new Scanner(is); Scanner delimitedScanner = scanner.useDelimiter("\\A");) {
            return scanner.hasNext() ? scanner.next() : "";
        }
    }

And findbugs plugin says:

Redundant nullcheck of value known to be non-null This method contains a redundant check of a known non-null value against the constant nul

And points on this:

return scanner.hasNext() ? scanner.next() : "";
        } //this line contains bug!!!
    }

Look at the pic:

enter image description here

And eclipse shows the same warning:

enter image description here

like image 915
Tony Avatar asked Oct 29 '22 14:10

Tony


2 Answers

The try-with-resources constructs confuses code analyzers and coverage tools that look directly at the byte code. At the end of the try-with-resources block a lot of extra byte code is generated that will have the ending brace as its line number.

Apparently FindBugs seems to think there is a problem there. However, this is almost certainly not the case.

The same thing happens with coverage tools, even though the block is fully covered, they claim that not all branches were covered. This is because the try-with-resources block adds handling for exceptional cases or resources being null which you can't really get covered properly with for example Unit tests.

like image 108
john16384 Avatar answered Nov 15 '22 05:11

john16384


The problem lies with the JDK which rewrites try-with-resources to the form:

Scanner scanner = null
try {
   scanner = new Scanner(is);
} finally {
  if (null != scanner) {try {scanner.close();} catch (Exception e) {...}}
}

Seems like this should already be fixed, so please check your findbugs plugin version. (https://sourceforge.net/p/findbugs/bugs/1169/)

like image 39
NickL Avatar answered Nov 15 '22 05:11

NickL