10
下面的代碼工作正常:投擲的RuntimeException與Optional.orElseThrow
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從可選:
Stream.of("key1", "key2")
.map(key -> Optional.ofNullable(someService.find(key))
.orElseThrow(() -> new RuntimeException("No entity found with key: " + key)))
// ...
我得到一個編譯時錯誤:
Error:(129, 33) java: unreported exception X; must be caught or declared to be thrown
兩者都拋出RuntimeException,任何想法爲什麼使用Optional的方法不起作用?
更新:我的基礎設施建設,我試着用的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"
您使用的是哪個Java版本?對我來說這工作正常Java 8_60 –
似乎是一個重複的http://stackoverflow.com/questions/25523375/java8-lambdas-and-exceptions –
它可能對我有用,因爲我嘗試與日食。在相關的問題中,他們說臭蟲不會影響月食。 –