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

  • SonarLint for Eclipse 4.1.0.201901311043
  • 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();
    }

Hi,
indeed, this method is not supported currently and I could not find a strong argument why not.
Therefore, ticket created to add support for this one : https://jira.sonarsource.com/browse/SONARJAVA-3144

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.