Homewrecker
Homewrecker

Reputation: 1106

Optionals with unchecked exceptions

Consider the following code:

auditlog.getMessages()
    .stream()
    .filter(m -> messageId.equals(m.getMessageid()))
    .findFirst()
    .orElseThrow(NoMessageFoundException::new)

NoMessageFoundException is a custom unchecked exception, extending from RuntimeException. When findFirst() returns an empty optional I expect a NoMessageFoundException to be thrown, however, the code just carries on.

Is it impossible to do this with unchecked exceptions?

I could change NoMessageFoundException to a checked exception, but then I would have to write a try/catch block or some sort of wrapper to catch the exception as explained here but I wish to not do that.

Any ideas?

Upvotes: 3

Views: 595

Answers (2)

if the exception is not getting throw is because there is at least one element remaining after the filter action...

see this example:

public class ASFasf {
    public static void main(String[] args) {
        List<Integer> l = Arrays.asList(1, 2, 3, 4, 5);
        Integer iR = l.stream().filter(x -> x > 100).findFirst().orElseThrow(NoMessageFoundException::new);
        System.out.println(iR);
    }
}

class NoMessageFoundException extends RuntimeException {
    public NoMessageFoundException() {
        super("Opala!!");
    }
}

iR will never get printed, and a NoMessageFoundException is thrown....

Upvotes: 1

Chadi
Chadi

Reputation: 787

There is no limitation on the type of Exception that can be thrown.

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
    if (value != null) {
        return value;
    } else {
        throw exceptionSupplier.get();
    }
}

If the code "carries on", it means that a message is found.

Upvotes: 2

Related Questions