Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 orElseThrow: why is compiler not complaining that method does not have a "throws" [duplicate]

Tags:

java

exception

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?

like image 926
releseabe Avatar asked Jan 01 '23 19:01

releseabe


1 Answers

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.

like image 57
xingbin Avatar answered Jan 05 '23 16:01

xingbin