Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to throw a `checked` exception when using Java Optional ifPresentOrElse method

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 ?

like image 890
hd84335 Avatar asked Dec 03 '22 17:12

hd84335


1 Answers

You must add the throw with square brackets:

*() -> { throw new BookNotFoundException(); }*
like image 165
Feliciano Júnior Avatar answered Dec 26 '22 12:12

Feliciano Júnior