Throw RuntimeException inside Stream with Optional.orElseThrow

喜夏-厌秋 提交于 2019-12-05 12:57:24

问题


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;
   })
   // ...

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:

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

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

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"

回答1:


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



来源:https://stackoverflow.com/questions/39076077/throw-runtimeexception-inside-stream-with-optional-orelsethrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!