Let's say there's an Optional
optString. Now if I use it as below:
optString.ifPresent({
//some statements
}, () -> throw new Exception());`, it fails to compile.
Why do I've to wrap the throw new Exception()
inside curly braces {}
.
Why can't I simply do () -> throw new Exception
.
Why is the compiler treating throw
and new
as some states that should be in a block?
In IntelliJ it fails with compilation errors: expected ) expected { expected;
and Unexpected token
A complete example:
class OptionalTest {
Optional<String> testString() {
return Optional.empty();
}
void getString() {
var optStr = testString();
optStr.ifPresentOrElse(s -> {
}, () -> throw new RuntimeException());
}
}