[FP/java:S2201] Optional.orElseThrow() return value must be used

  • What language is this for?
    Java
  • Which rule?
    S2201
  • Why do you believe it’s a false-positive?
    I often use the Optional.orElseThrow() method to validate a object
  • Are you using
    • SonarLint 3.15.1
    • VSCode 1.75.1
  • How can we reproduce the problem? Give us a self-contained snippet (best) or screenshot (good)

Minimal setup:

Optional.empty().orElseThrow(() -> new Exeption()); // FP

Real world example:

// check unused inputs
for (String input : getInputSchema().keySet()) {
	propertyJoints.stream()
		.filter(joint -> joint.getPreviousTaskId().equals(SubTaskId.INPUT))
		.filter(joint -> joint.getPreviousProperty().equals(input))
		.findAny()
		.orElseThrow(() -> new IllegalArgumentException("Input property " + input + " is unused")); // FP
}
1 Like

Hi Hauke,

thanks for reporting! I could reproduce the issue and confirm that this is a current limitation in our analyzer. The rule should report on methods without side effects only. However, for methods with a throws clause it is an intended side effect to throw exceptions. The rule should ignore them.

I created a ticket for this issue: [SONARJAVA-4431] - Jira

Regards,
Marco

Thank you. Do you have any idea of a timeline for fixing this? Frustratingly this issue was first raised over 2 years ago java:S2201 False positive on orElseThrow - #4 by alban.auzeill