如何在消费者中抛出异常 Java 8

How to throw an Exception in a Consumer Java 8

在 java 8 中使用消费者时有什么方法可以抛出异常吗?

例如:

    private void fooMethod(List<String> list) throws Exception {

    list.forEach(element->{
        if(element.equals("a")) {
            throw new Exception("error!");
        }
    });

}

这给了我一个编译器错误:未处理的异常类型 Exception

在这种情况下抛出异常的正确方法是什么?

由于Exception及其子类(RuntimeException除外)是checked Exception并且在lambda中,你不能抛出checked exception。因此你应该使用 RuntimeException:

private void fooMethod(List<String> list) throws Exception {
    list.forEach(element->{
        if(element.equals("a")) {
            throw new RuntimException("error!");
        }
    });
}

Streams 和相关 类 并非设计用于使用已检查的异常。但是任何 RuntimeException 都可以在代码中的任何点抛出,因此诀窍是抛出一个运行时,其原因(异常链接)是适当的检查异常:

private void fooMethod(List<String> list) throws Exception {   
    list.forEach(element->{
        if(element.equals("a")) {
            throw new Runtime(new Exception("error!"));
        }
    });  
}

然后在捕获代码中你只需要封装原始的检查异常:

try {
    fooMethod(someList);
} catch(Throwable e) {
    Exception ex = e.getCause();
}

您可以使用 apache commons-lang3 库来完成。

https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/function/Failable.html

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

你可以这样写:

import org.apache.commons.lang3.function.Failable;

private void fooMethod(List<String> list) throws Exception {
    list.forEach(Failable.asConsumer(element->{
        if(element.equals("a")) {
            throw new Exception("error!");
        }
    }));
}