Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

lambda

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.

like image 749
cuh Avatar asked May 18 '26 02:05

cuh


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);
    }));
like image 143
Dónal Avatar answered May 20 '26 14:05

Dónal