从 lambda 抛出异常 [英] Throwing exception from lambda
问题描述
鉴于此 java 8 代码
Given this java 8 code
public Server send(String message) {
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> {
try {
basic.sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
});
return this;
}
我们如何正确地将这个 IOException
委托给方法调用的堆栈?(简而言之,如何让这个方法抛出这个 IOException
?)
how do we properly make this IOException
be delegated up the stack of the method call? (in nutshell how to make this method throw this IOException
?)
java 中的 Lambdas 看起来对错误处理不太友好......
Lambdas in java does not look very friendly to error handling...
推荐答案
我的方法是偷偷地从 lambda 中抛出它,但要注意让 send
方法在其 throws
子句中声明它.使用 Exceptional
类我在这里发布:
My approach would be to sneakily throw it from the lambda, but take care to have the send
method declare it in its throws
clause. Using the Exceptional
class I posted here:
public Server send(String message) throws IOException {
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> Exceptional.from(() -> basic.sendText(message)).get());
return this;
}
通过这种方式,您可以有效地让编译器移开视线",在代码中的某个位置禁用其异常检查,但是通过在 send
方法中声明异常,您恢复所有调用者的正常行为.
This way you're effectively making the compiler "look away" for just a bit, disabling its exception checking at one spot in your code, but by declaring the exception on your send
method, you restore the regular behavior for all its callers.
这篇关于从 lambda 抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!