7

鉴于此 java 8 代码

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?)

java中的Lambdas看起来对错误处理不是很友好......

4

3 回答 3

10

我的方法是偷偷地将它从 lambda 中抛出,但请注意让该send方法在其throws子句中声明它。使用我在这里发布Exceptional的课程:

public Server send(String message) throws IOException {
  sessions.parallelStream()
          .map(Session::getBasicRemote)
          .forEach(basic -> Exceptional.from(() -> basic.sendText(message)).get());
  return this;
}

这样,您就可以有效地使编译器“移开视线”一点,在代码中的某个位置禁用其异常检查,但是通过在send方法上声明异常,您可以恢复所有调用者的常规行为。

于 2015-07-26T14:35:18.023 回答
5

我为 Stream API编写了一个扩展,它允许抛出检查的异常。

public Server send(String message) throws IOException {
    ThrowingStream.of(sessions, IOException.class)
        .parallelStream()
        .map(Session::getBasicRemote)
        .forEach(basic -> basic.sendText(message));

    return this;
}
于 2015-07-29T16:32:57.307 回答
2

问题确实是@FunctionalInterfacelambdas 中使用的所有 s 都不允许抛出异常,除了未经检查的异常。

一种解决方案是使用我的软件包;有了它,您的代码可以读取:

sessions.parallelStream()
    .map(Session::getBasicRemote)
    .forEach(Throwing.consumer(basic -> basic.sendText(message)));
return this;
于 2015-07-26T14:11:16.753 回答