从 lambda 抛出异常

Throwing exception from lambda

鉴于此 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 中的 Lambda 看起来对错误处理不是很友好...

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

一种解决方案是使用a package of mine;有了它,您的代码可以阅读:

sessions.parallelStream()
    .map(Session::getBasicRemote)
    .forEach(Throwing.consumer(basic -> basic.sendText(message)));
return this;

我的方法是 偷偷地 从 lambda 中抛出它,但要注意让 send 方法在其 throws 子句中声明它。使用 Exceptional class :

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

通过这种方式,您可以有效地使编译器 "look away" 稍微有效,在代码中的某个位置禁用其异常检查,但是通过在 send 方法上声明异常,您恢复其所有调用者的常规行为。

wrote an extension 到 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;
}