Rule java:S2259: False-positive NullPointerException bug logged when variable is null-checked by an imported method

Product: SonarCloud
Rule: java:S2259


Per this post in another thread, here is a segment of reproducible code:

        String test = null;
        checkNotNull(test, "This imported method will throw an exception because string `test` is null, hence the next line will not evaluate.");
        char unused = test.charAt(0);

We have noted that the issue does not arise if the imported method’s definition is used directly; the issue is due to SonarCloud not properly handling the outcome using the imported method definition.

        String test2 = null;
        if (test2 == null)
            throw new PermissibleArgumentException(String.valueOf("This will throw an exception because string `test` is null"));
        char unused2 = test2.charAt(0);

The imported method is a helper/convenience function and does what it is intended to do.

Should SonarCloud be able to determine that there is no NullPointerException risk in the first reproducible code sample (without the addition of a comment to tell SonarCloud to avoid adding a bug for this line of code)?

Thank you!


Note that the checkNotNull method definition is in the 2nd code segment, also here explicitly:

    public static <T> T checkNotNull(@Nullable T reference, @Nullable String errorMessage)
        if (reference == null)
            throw new PermissibleArgumentException(String.valueOf(errorMessage));
        return reference;

Using Sonarqube 9.4

Another example:

    HttpEntity<T> httpRequest = new HttpEntity<>(request, HTTP_HEADERS);
    ResponseEntity<Foo> response = restTemplate.postForEntity(serverUrl + "/odata/folders", httpRequest, Foo.class);

    if (!response.hasBody() || response.getStatusCode() != HttpStatus.CREATED) {
      throw new ReportingException("bla");
    return response.getBody().toEntity();

Sonarqube complains about the response.getBody() call might return null, but response.hasBody() already does the null check before.