spotbugs icon indicating copy to clipboard operation
spotbugs copied to clipboard

False positive NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE when throwing exceptions

Open aochsner opened this issue 7 years ago • 3 comments

I have to be missing something here but this is what I'm observing using Spotbugs version 3.1.12

Why does SpotBugs mark errorWhenThrowing as referencing a NP?

package com.foo.bar;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/** testing spotbugs. */
public class SpotbugsTest {

  /**
   * this works.
   *
   * @return
   */
  public String noErrorWhenReturn() {
    ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
    String body = response.getBody();
    if (body == null) {
      return null;
    }
    return body;
  }

  /**
   * This does not.
   *
   * @return
   */
  public String errorWhenThrowing() {
    ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
    String body = response.getBody();
    if (body == null) {
      throw new NullPointerException("fail");
    }
    return body;
  }

  /**
   * this works but forces me to nest in ways I don't like.
   *
   * @return
   */
  public String noErrorWhenNested() {
    ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
    String body = response.getBody();
    if (body != null) {
      return body;
    }
    throw new NullPointerException("fail");
  }
}

[ERROR] Possible null pointer dereference in com.foo.bar.SpotbugsTest.errorWhenThrowing() due to return value of called method [com.foo.bar.SpotbugsTest, com.foo.bar.SpotbugsTest, com.foo.bar.SpotbugsTest] Checked and found to be null at SpotbugsTest.java:[line 31]Null value at SpotbugsTest.java:[line 31]Known null at SpotbugsTest.java:[line 30] NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE

aochsner avatar May 21 '19 16:05 aochsner

Thanks for opening your first issue here! :smiley: Please check our contributing guideline. Especially when you report a problem, make sure you share a Minimal, Complete, and Verifiable example to reproduce it in this issue.

welcome[bot] avatar May 21 '19 16:05 welcome[bot]

JDK 8 btw

aochsner avatar May 21 '19 17:05 aochsner

I think it is similar to #1087.

If you check the package-info.java file for that package (https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/http/package-info.java), you'll find that it has annotations indicating that all parameters should be non-nullable by default.

According to the documentation, method getBody() is annotated with @Nullable.

This is not a FP of SpotBugs.

Xiaoven avatar May 26 '21 12:05 Xiaoven