从 lambda 抛出异常 [英] Throwing exception from lambda

查看:51
本文介绍了从 lambda 抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此 java 8 代码

Given this java 8 code

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

how do we properly make this IOException be delegated up the stack of the method call? (in nutshell how to make this method throw this IOException ?)

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

Lambdas in java does not look very friendly to error handling...

推荐答案

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

My approach would be to sneakily throw it from the lambda, but take care to have the send method declare it in its throws clause. Using the Exceptional class I posted here:

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

通过这种方式,您可以有效地让编译器移开视线",在代码中的某个位置禁用其异常检查,但是通过在 send 方法中声明异常,您恢复所有调用者的正常行为.

This way you're effectively making the compiler "look away" for just a bit, disabling its exception checking at one spot in your code, but by declaring the exception on your send method, you restore the regular behavior for all its callers.

这篇关于从 lambda 抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆