从lambda抛出exception

鉴于此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对error handling看起来不太友好……

我的方法是偷偷地从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; } 

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

我写了一个 Stream API 的扩展 ,它允许抛出已检查的exception。

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

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

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

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