Geek
Geek

Reputation: 27219

Why does FindBugs raise a critical warning when explicitly throwing a NPE?

Consider the following from FindBugs error desriptions

NP: Null value is guaranteed to be dereferenced (NP_GUARANTEED_DEREF)

There is a statement or branch that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).

Note that a check such as if (x == null) throw new NullPointerException(); is treated as a dereference of x.

What is meant by except on forward paths involving run time exceptions ?

Also why a check like if (x == null) throw new NullPointerException(); raise an warning?

Upvotes: 2

Views: 529

Answers (1)

David Harkness
David Harkness

Reputation: 36562

Consider this horribly contrived code:

String value = null;
if (5 > 8) {
    value = "foo";
}
doSomething();
if (value.equals("foo")) {
    System.out.println("value is foo");
}

Static analysis can prove that value will be null when equals is called, causing a NullPointerException to be thrown. However, if the call to doSomething() results in a thrown runtime exception, the call to equals will never be reached. This is the meaning of "except on forward paths involving runtime exceptions."

As for your second question, FindBugs issues a warning for this code

if (value == null) {
    throw new NullPointerException();
}

because the effect is the same as what happens when you dereference a null value. Since the dereference merits a warning, so does any code which mimics that dereference.

Upvotes: 3

Related Questions