使用 Optional.orElseThrow 在 Stream 中抛出 RuntimeException
2022-09-02 22:02:38
以下代码工作正常:
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;
})
// ...
但是,当我使用 orElseThrow from Optional 时:
Stream.of("key1", "key2")
.map(key -> Optional.ofNullable(someService.find(key))
.orElseThrow(() -> new RuntimeException("No entity found with key: " + key)))
// ...
我收到编译时错误:
错误:(129, 33) java: 未报告异常 X;必须被捕获或声明被抛出
两者都抛出了一个运行时异常,任何想法为什么与可选的方法不起作用?
更新:我的构建基础设施,我试图用IntelliJ和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"