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.