mebigfatguy / fb-contrib

a FindBugs/SpotBugs plugin for doing static code analysis for java code bases
http://fb-contrib.sf.net
GNU Lesser General Public License v2.1
157 stars 45 forks source link

False positives for try-with-resources (NP_LOAD_OF_KNOWN_NULL_VALUE, RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE) #462

Closed nmatt closed 10 months ago

nmatt commented 10 months ago

This happens with sb-contrib version 7.6.4 (current release) and OpenJDK 17 (Eclipse Temurin).

Example code:

public final class Example
{
    public static String example(String resource)
    {
        try (InputStream input = Example.class.getResourceAsStream(resource))
        {
            if (input == null)
            {
                return null;
            }
            else
            {
                return new String(input.readAllBytes(), StandardCharsets.ISO_8859_1);
            }
        }  // bugs reported on this line
        catch (IOException ex)
        {
            throw new UncheckedIOException(ex);
        }
    }
}

NP_LOAD_OF_KNOWN_NULL_VALUE and RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE are incorrectly reported, due to the null test. These false positives are probably caused by the try-with-resources byte code. Null resource values are valid in try-with-resources statements. Due to the scope of the resource variable, it would be inconvenient to move the null check outside the try-with-resources statement.

Applying @SuppressFBWarnings to just the resource variable declaration also doesn't work.

mebigfatguy commented 10 months ago

This is part of SpotBugs itself, please post the issue here

https://github.com/spotbugs/spotbugs/issues

nmatt commented 10 months ago

Resubmitted as SpotBugs issue: https://github.com/spotbugs/spotbugs/issues/2836