Optional::orElseThrow should be considered when deciding if Iterator::next throws NoSuchElementException

1,014 views
Skip to first unread message

ry...@rmarcus.info

unread,
Oct 21, 2016, 12:00:24 PM10/21/16
to SonarLint
Hi,

I'm not sure if this is the appropriate place to report this, but I believe I've found a small false positive.

With the following implementation of an Iterator's next method:

public SomeType next() {
   
return getOptionalForNext().orElseThrow(NoSuchElementException::new);
}

... where getOptionalForNext returns an Optional<SomeType>, Sonar complains:

Add a "NoSuchElementException" for iteration beyond the end of the collection.

Not exactly sure how Sonar tracks which methods can throw runtime exceptions, and I know determining if any method called within next() throws a NoSuchElementException is probably impossible. But there should probably be support for Java-native methods that can throw those exceptions.

Manually checking if the Optional is present (with isPresent()) and then throwing a NoSuchElementException removes the warning.

Tested with the most recent Eclipse and SonarLint from the marketplace.

Thanks,

Ryan Marcus

Michael Gumowski

unread,
Oct 24, 2016, 3:40:51 AM10/24/16
to ry...@rmarcus.info, SonarLint
Hey Ryan,

Thanks a lot for your feedback and the reproducer. It's indeed a False Positive (FP) with rule S2272 implemented in the SonarQube Java Analyzer. 
I created the following ticket to handle it: SONARJAVA-1901

Cheers,

--
You received this message because you are subscribed to the Google Groups "SonarLint" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sonarlint+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sonarlint/5e1da9ad-385b-47a0-8fa2-f01bcc0f07e8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--

Michael GUMOWSKI | SonarSource
Software Developer @ Language Team
http://sonarsource.com
Reply all
Reply to author
Forward
0 new messages