Tony
Tony

Reputation: 479

Redundant nullcheck of value known to be non-null or possible bug in 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

Upvotes: 5

Views: 6533

Answers (2)

NickL
NickL

Reputation: 4276

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/)

Upvotes: 1

john16384
john16384

Reputation: 8044

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.

Upvotes: 1

Related Questions