从lambda抛出异常

vac*_*ach 6 java error-handling lambda checked-exceptions java-8

鉴于此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;
}
Run Code Online (Sandbox Code Playgroud)

我们如何正确地将它IOException委托给方法调用的堆栈?(简而言之,如何让这个方法抛出这个IOException?)

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

Mar*_*nik 9

我的方法是偷偷地从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;
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以有效地使编译器"远离"一点,在代码中的一个位置禁用其异常检查,但通过在send方法上声明异常,可以恢复所有调用方的常规行为.


Jef*_*rey 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;
}
Run Code Online (Sandbox Code Playgroud)