Does java:S2259 account for notnull assertions?

SQ 8.6

Does the analysis for rule java:S2259 (null pointer/object dereferencing) account for nullity assertions?

I’m getting a false positive in an admittedly convoluted piece of code in which the code asserts a local variable is not null, wraps that in a try, and the catch calls a default constructor and assigns that to the variable. But S2259 still says the variable could be null when it is later deferenced.

Yes, if you assert that something is not null using for example an assert statement or methods like Objects.requireNonNull, S2259 will take that into account. It also takes into account the control flow of try-catch statements.

We can illustrate this with the following silly example code, which works fine (meaning it does not raise an FP):

private String foo(@Nullable Object arg) {
  // Round about way of writing `if (arg == null) arg = "";`:
  try {
    Objects.requireNonNull(arg);
  } catch (Exception e) {
    arg = "";
  }
  return arg.toString();
}

If a potential null pointer dereferencing is wrapped in a try block, is the rule supposed to be flagged still? For instance, I have:

image

Note there are no further dereferences of the variable “context” – I think the coder’s thinking was that context could be null or close() could throw an exception, so just handle both cases with one catch.