从lambda抛出异常 [英] Throwing exception from lambda

查看:169
本文介绍了从lambda抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这个java 8代码

  public Server send(String message){
sessions.parallelStream()
.map(Session :: getBasicRemote)
.forEach(basic - > {
try {
basic.sendText(message);
} catch(IOException e) {
e.printStackTrace();
}
});

返回此;
}

我们如何正确地使这个 IOException 委托给方法调用的堆栈? (简而言之,如何使这个方法抛出这个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆