java:S2201 False positive on orElseThrow

Versions used:

  • SonarCloud
  • Sonar Gradle plugin 3.1.1
  • Analysis runs on JDK 14

Simplified snippet:

attachmentPoints.stream()
    .filter(point -> satisfiesCosntraint(point))
    .findAny()
    .orElseThrow(() -> new CantileverRuleViolationException("None of the attachment points satisfy the constraint"));

The orElseThrow statement is reported as a violation:

When the call to a function doesn’t have any side effects, what is the point of making the call if the results are ignored?

However, in this case, there is a side effect - an exception is thrown.

Hi Gediminas,

The rule sees that you try to find something in a stream without using it. Perhaps a developer could also not understand why instantly.
So I would not consider this issue as false-positive and I would change the code to:

    if (attachmentPoints.noneMatch(point -> satisfiesCosntraint(point))) {
      throw new CantileverRuleViolationException("None of the attachment points satisfy the constraint");
    }

It reflects better that the only purpose is to raise an exception.

I do not agree. If you convert the orElseThrow into an “if” statement, you add complexity. Optional is designed just to avoid it. Moreover, the orElseThrow has the same kind of usage of

Objects.requireNonNull(object, ()->"message")

By the way Objects is not in the list of objects triggering the issue. In my opinion both or neither should trigger an issue: one yes and the other no does not make sense.
What you say is reasonable when the last method invoked is orElse or orElseGet, not orElseThrow.