Why does a Java Lambda which throws a Runtime Exce

2019-05-02 18:45发布

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?

1条回答
冷血范
2楼-- · 2019-05-02 19:31

The Java Language Specification describes the body of a lambda expression

A lambda body is either a single expression or a block (§14.2).

This, however,

throw new IllegalArgumentException("fail")

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).

查看更多
登录 后发表回答