How to throw exception from lambda expression using .orElseThrow in Java

Viewed 493

I got a compilation failure

Compilation failure
[ERROR]  unreported exception java.lang.Throwable; must be caught or declared to be thrown

Why does this code not compile

Collections.singletonList(Arrays.asList("a", "b", "c")
    .stream()
    .findAny()
    .orElseThrow(() -> {
        String msg = "Failed";
        throw new IllegalArgumentException(msg);
    }));

while this seems okay

Collections.singletonList(Arrays.asList("a", "b", "c")
    .stream()
    .findAny()
    .orElseThrow(() -> new IllegalArgumentException("Failed")));

is this related to https://bugs.openjdk.java.net/browse/JDK-8056983 or is the first code block wrong?

In VS Code and in Eclipse I do not get a syntax error from the IDE.

1 Answers

The two code snippets are different. In the first one, you throw an exception in the lambda. In the second one, you return an exception from the lambda.

To make the two snippets consistent, change the first one to

Collections.singletonList(Arrays.asList("a", "b", "c")
    .stream()
    .findAny()
    .orElseThrow(() -> {
        String msg = "Failed";
        return new IllegalArgumentException(msg);
    }));
Related