从lambda抛出异常 [英] Throwing exception from lambda
问题描述
public Server send(String message){
sessions.parallelStream()
.map(Session :: getBasicRemote)
.forEach(basic - > {
try {
basic.sendText(message);
} catch(IOException e) {
e.printStackTrace();
}
});
返回此;
}
我们如何正确地使这个 IOException $将c $ c>委托给方法调用的堆栈? (简而言之,如何使这个方法抛出这个
IOException
?)
java中的Lambdas看起来不太友善错误处理...
我的方法是将从lambda中抛出,请注意让发送
方法在其 throws
子句中声明它。使用特殊
类我在这里发贴:
public Server send(String message)throws IOException {
sessions.parallelStream()
.map(Session :: getBasicRemote)
.forEach(basic - > Exceptional.from(() - > basic.sendText(message))。get());
返回这个;
}
这样你就有效地使编译器看起来只是一个在代码中的一个位置禁用其异常检查,但是通过在发送
方法上声明异常,您可以恢复所有调用者的常规行为。
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;
}
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
?)
Lambdas in java does not look very friendly to error handling...
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;
}
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屋!