从lambda抛出异常

时间:2015-07-26 14:07:46

标签: java error-handling lambda java-8 checked-exceptions

鉴于此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对错误处理看起来不太友好......

3 个答案:

答案 0 :(得分:8)

我的方法是偷偷地从lambda中抛出它,但要注意让UITextView.contentOffset方法在其send子句中声明它。使用throwsI posted here

Exceptional

通过这种方式,您可以有效地使编译器“远离”#34;稍等一下,在代码中的一个位置禁用其异常检查,但通过在public Server send(String message) throws IOException { sessions.parallelStream() .map(Session::getBasicRemote) .forEach(basic -> Exceptional.from(() -> basic.sendText(message)).get()); return this; } 方法上声明异常,可以恢复所有调用方的常规行为。

答案 1 :(得分:5)

I 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;
}

答案 2 :(得分:2)

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

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

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