[False Positive]A "NullPointerException" could be thrown;

  • versions used (SonarQube, Scanner, language analyzer) - SonarQube 8.9
  • Language - Java 8
  • Failing Rule - A “NullPointerException” could be thrown;
  • minimal code sample to reproduce (with analysis parameter, and potential instructions to compile).
try (Connection connection = jdbcTemplate.getDataSource()!=null ? jdbcTemplate.getDataSource().getConnection(): null;){
}

This throws an error “A “NullPointerException” could be thrown; “getDataSource()” can return null.”. The null check is already in place and the getConnection will be called only if the getDataSource is not null.

Condition 2:

if (null == responseEntity || null == responseEntity.getBody() || (!(responseEntity.getBody() instanceof LinkedHashMap)
                || !((LinkedHashMap<String, String>) responseEntity.getBody()).containsKey("access_token")) ) 

For this condition the error says : ‘“getBody” is nullable here’ even though there is a null check on getBody()

1 Like

Hello @Bhuvana

The analyzer assumes that two consecutive method calls do not necessarily return the same value.
It means that a null check on the first call to getBody() is not enough to avoid a NPE. You should extract the method call into a variable to not have an issue.

In a way, this is a limitation of the analyzer, it is not able to detect if a method always returns the same value or not, so it reports an issue anyway, taking the risk to report false positives. If you are confident your code is fine as it is, you can resolve the issue as false positive. As we improve our analyzer, we might eventually support such situations.

I like to see it in a more optimistic way: you should not consider that a method always returns the same value, even if you know it is the case, a future modification could break this contract. In addition, if the method hides computation, you could spare it by extracting it to a variable.

Hope it clarifies the situation.
Best,
Quentin

1 Like

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