使用Optional.orElseThrow将Stream中的RuntimeException抛出 [英] Throw RuntimeException inside Stream with Optional.orElseThrow

查看:1497
本文介绍了使用Optional.orElseThrow将Stream中的RuntimeException抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以正常工作:

The following code works fine:

Stream.of("key1", "key2")
   .map(key -> {
      SomeObject foo = service.find(key);
      if (foo == null) {
         throw new RuntimeException("No entity found with key: " + key);
      }
      return foo;
   })
   // ...

但是,当我使用Optional中的orElseThrow时:

However, when I use orElseThrow from Optional:

Stream.of("key1", "key2")
   .map(key -> Optional.ofNullable(someService.find(key))
         .orElseThrow(() -> new RuntimeException("No entity found with key: " + key)))
   // ...

我收到一个编译时错误:

I get a compile time error:

错误:(129,33)java:未报告的异常X;必须被抓住或 宣布要扔掉

Error:(129, 33) java: unreported exception X; must be caught or declared to be thrown

两者都抛出RuntimeException,为什么使用Optional的方法不起作用?

Both throw a RuntimeException, any ideas why the approach with Optional doesn't work?

更新:我的构建基础结构,我尝试使用IntelliJ和Maven对其进行编译:

Update: My build infrastructure, I tried to compile it with IntelliJ and Maven:

$ mvn -version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T17:41:47+01:00)
Maven home: C:\Tools\apache-maven-3.3.9
Java version: 1.8.0_91, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_91\jre
Default locale: de_AT, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"

推荐答案

这是一个编译器错误 JDK-8047338 可以阻止正确的通用异常类型推断.在1.8.0_92版本中已部分解决.

This is a compiler bug JDK-8047338 which prevent correct generic exception type inference. It was partially resolved in 1.8.0_92 release.

这篇关于使用Optional.orElseThrow将Stream中的RuntimeException抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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