4

I have the following code:

public Trail getNewestTrail() { return trails.stream().max(Comparator.comparing(Trail::getTimestamp)).orElseThrow(NoSuchElementException::new); } 

I am not seeing any error without having getNewestTrail declared as throwing the exception -- why?

0

2 Answers 2

8

NoSuchElementException extends from java.lang.RuntimeException, it is uncheched exception:

Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses)

you only need specify checked exception in method signature.

Sign up to request clarification or add additional context in comments.

6 Comments

Given that without the orElseThrows I get a compile error which says I should use Optional instead of Trail, should I add the throws to the method signature anyway?
@releseabe If you expect an exceptio be thrown when there is non max element found, you can use orElseThrow and need not use throws in the signature.
Would we not want the caller to know about the potential of the exception?
@releseabe If you want the caller notice that, you need throw a checked exception. Then you have to use throws in the signature. Otherwise the complier will complain.
I am puzzled that I have to add the orElseThrows and yet it is an unchecked exception.
|
1

NoSuchElementException is a RuntimeException and they need not be handled at compile time.

Just to check, replace NoSuchElementException with Exception and it will start giving you a compilation failure.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.