I understand that a lambda in java cannot throw a checked exception, but can throw a RuntimeException, but why does the below code require brackets?
Map<String, Integer> m = new HashMap<>();
Integer integer = m.computeIfAbsent("", s -> {throw new IllegalArgumentException("fail");});
Why can't you have?
m.computeIfAbsent("", s -> throw new IllegalArgumentException("fail"));
Is it due to the assumption of the compiler that it would return in this instance an int, so therefor can't have a return of an exception, even though its thrown?
The Java Language Specification describes the body of a lambda expression
This, however,
is the
throw
statement, not an expression. The compiler therefore rejects it as the lambda expression's body.You can go down the rabbit hole and learn what all the types of expressions are, here (follow the grammar).