"value" is nullable here incorrectly reported after calling method that throws


(Liam Sharp) #1
  • SonarLint for Eclipse
  • Eclipse Oxygen.3a Release (4.7.3a)
  • commons-lang3 3.8.1
  • guava 27.0.1-jre

The code below triggers a potential NullPointerException.

Using an assert before hand removes the error, as this throws AssertionError the code isn’t reachable which makes sense to me.

Likewise calling Validate.notNull also prevents the issue.

However, calling Verify.verifyNotNull doesn’t, Sonar doesn’t seem to be able to spot this. Looks like a bug to me?

    public static int test()
        final Map<String, String> map = new HashMap<>();

        String value = null;

        if (map.containsKey("foo"))
            value = map.get("foo");
        assert value != null; // Prevents Sonar warning
        Validate.notNull(value); // Prevents Sonar warning
        Verify.verifyNotNull(value); // Does not prevent Sonar warning

        // A "NullPointerException" could be thrown; "value" is nullable here.
        return value.length();