Home > Software engineering >  How to Log error and throw an exception inside orElseThrow() clause?
How to Log error and throw an exception inside orElseThrow() clause?

Time:03-21

I'd like to log an error and throw an exception inside orElseThrow() clause. I need to prepare proper supplier:

Working code:

Optional<Integer> op = Optional.of(24832);
op.orElseThrow(() -> new RuntimeException());

How to log an error and throw an exception at once:

op.orElseThrow({
        Logger.error("Incorrect value");
        () -> new RuntimeException();
        });

CodePudding user response:

orElseThrow requires a Supplier as parameter: https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Optional.html#orElseThrow(java.util.function.Supplier)

So you can use either

orElseThrow(RuntimeException::new)
orElseThrow(() -> new RuntimeException())

or if you need additional code inside the lambda, a regular code block. Since you need to supply a value, the code block needs to return that value at the end:

orElseThrow(() -> {
    Logger.error("Incorrect value");
    return new RuntimeException();
})
  • Related