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?

xingbin
  • 27,410
  • 9
  • 53
  • 103
releseabe
  • 323
  • 3
  • 13

2 Answers2

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.

user85421
  • 28,957
  • 10
  • 64
  • 87
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • 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 Sep 28 '18 at 06:44
  • @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. – xingbin Sep 28 '18 at 06:48
  • Would we not want the caller to know about the potential of the exception? – releseabe Sep 28 '18 at 06:54
  • 2
    @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. – xingbin Sep 28 '18 at 06:59
  • I am puzzled that I have to add the orElseThrows and yet it is an unchecked exception. – releseabe Sep 28 '18 at 07:14
  • @releseabe It's no necessary to use orElseThrows clause. You can just let this method return `Optional` and let the caller check if the max element exists. – xingbin Sep 28 '18 at 07:19
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.

Rishikesh Dhokare
  • 3,559
  • 23
  • 34