Why a checked Exception can't be thrown in the orElse part when using ifPresentOrElse
java Optional method ?
For example:
dao.findBook(id).ifPresentOrElse(book -> {
printingService.print(book, printerName);
changeBookPrintDate(book.getId(), LocalDateTime.now());
}, () -> new BookNotFoundException());
where BookNotFoundException
is a custom exception extending Exception
class (checked exception).
but this code makes the compiler upset:
unreported exception com...exception.BookNotFoundException; must be caught or declared to be thrown
(knowing that it is already thrown in the method declaration, and surrounding this block with try catch doesn't resolve the compilation problem).
But if we make BookNotFoundException
to be extending RuntimeException
(which is unchecked), then all works perfectly.
Anyone knows why ?
What's the reason that prevents throwing such kind of exceptions in this java 9 Optional method ?
And why should I make my exception a RuntimeException to make it works while it is more to be considered a 'custom exception' more than it is 'runtime' ?
This question is addressing the same problem but for java 8 lambdas, so I don't know if the same applies for java 9 Optionals.
Other researches leaded nowhere other than confirming that it is not possible.
Any Idea ?
You must add the throw with square brackets:
*() -> { throw new BookNotFoundException(); }*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With