Java8 Lambda 和异常 [英] Java8 Lambdas and Exceptions
问题描述
我想知道是否有人可以向我解释以下奇怪之处.我使用的是 Java 8 更新 11.
I wonder if someone could explain the following weirdness to me. I'm using Java 8 update 11.
给定这个方法
private <F,T> T runFun(Function<Optional<F>, T> fun, Optional<F> opt) {
return fun.apply(opt) ;
}
如果我首先构造一个函数对象,并将它传递给上面的方法,事情就会编译.
If I first construct a function Object, and pass that in to the method above, things compile.
private void doesCompile() {
Function<Optional<String>, String> fun = o -> o.orElseThrow(() -> new RuntimeException("nah"));
runFun(fun, Optional.of("foo"));
}
但是,如果我将函数内联为 lambda,编译器会说
But, if I inline the function as a lambda, the compiler says
未报告的异常 X;必须被捕获或声明被抛出
unreported exception X; must be caught or declared to be thrown
private void doesNotCompile () {
runFun(o -> o.orElseThrow(() -> new RuntimeException("nah")), Optional.of("foo"));
}
<小时>
更新:原来错误消息是由 maven 缩写的.如果直接用javac编译,则报错:
Update: Turns out the error message was abbreviated by maven. If compiled directly with javac, the error is:
error: unreported exception X; must be caught or declared to be thrown
runFun(o -> o.orElseThrow(() -> new RuntimeException("nah")), Optional.of("foo"));
^
where X,T are type-variables:
X extends Throwable declared in method <X>orElseThrow(Supplier<? extends X>)
T extends Object declared in class Optional
另请参阅此处,了解可运行的测试代码.
Also see here for runnable test code.
推荐答案
这就是为我解决问题的方法:
This is what solved the problem for me:
代替写作
optional.map(this::mappingFunction).orElseThrow(() -> new BadRequestException("bla bla"));
我写道:
optional.map(this::mappingFunction).<BadRequestException>orElseThrow(() -> new BadRequestException("bla bla"));
添加显式
有助于解决这些 lambda 边缘情况(这很烦人...)
Adding the explicit <BadRequestException>
helps with these lambda edge cases (which are quite annoying...)
更新:这是为了防止您无法更新到最新的 JDK 版本,如果可以,您应该...
UPDATE: This is in case you can't update to the latest JDK version, if you can you should...
这篇关于Java8 Lambda 和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!