我有一些代码(有一些嵌套的forEach's
和streams
):
void process() throws RuntimeException
{
try {
ArrayList<Integer> ints = new ArrayList<>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.forEach(e -> {
System.out.println(e);
throw new RuntimeException("RuntimeException");
});
}
catch (RuntimeException rex)
{
rex.printStackTrace();
throw rex; // throw it up, and up, and up...
}
}
它不起作用,因为foreach's
Consumer's
accept()
默认情况下不会抛出异常。即使它有一个throws
签名 - 我也无法在街区外捕获它。
我需要做的是从foreach()
方法本身捕获异常。
如果没有像
这样的外部方法,我有什么办法可以做到这一点 void handleException(RuntimeException ex){ ... }
并在每个forEach()'s
try / catch中调用它?
答案 0 :(得分:2)
我发现问题是错误的 - 它确实适用于RuntimeException
。
对于已检查的例外情况,有一个正常工作的代码:
package Exporter;
import java.util.function.Consumer;
import java.util.function.Function;
public final class LambdaExceptions {
@FunctionalInterface
public interface Consumer_WithExceptions<T, E extends Exception> {
void accept(T t) throws E;
}
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
R apply(T t) throws E;
}
/**
* .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name))));
*/
public static <T, E extends Exception> Consumer<T> rethrowConsumer(Consumer_WithExceptions<T, E> consumer) throws E {
return t -> {
try {
consumer.accept(t);
} catch (Exception exception) {
throwActualException(exception);
}
};
}
/**
* .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
*/
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E {
return t -> {
try {
return function.apply(t);
} catch (Exception exception) {
throwActualException(exception);
return null;
}
};
}
@SuppressWarnings("unchecked")
private static <E extends Exception> void throwActualException(Exception exception) throws E {
throw (E) exception;
}
}
它就像一个魅力:
void process() throws RuntimeException
{
try {
ArrayList<Integer> ints = new ArrayList<>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.forEach(LambdaExceptions.rethrowConsumer(e -> {
System.out.println(e);
throw new RuntimeException("RuntimeException");
}));
}
catch (RuntimeException rex)
{
System.out.println("Got first exception");
rex.printStackTrace();
throw rex;
}
}