为什么引发运行时异常的Java Lambda需要括号? [英] Why does a Java Lambda which throws a Runtime Exception require brackets?
问题描述
Map< String,Integer> m = new HashMap<>();
整数integer = m.computeIfAbsent(,s - > {throw new IllegalArgumentException(fail);});
为什么不能?
m.computeIfAbsent(,s - > throw new IllegalArgumentException(fail));是由于假设编译器会在这个实例中返回一个int,所以这样做是由于
Java语言规范描述了一个lambda表达式的主体
lambda体是单个表达式或块(§14.2)。
然而,
throw new IllegalArgumentException(fail)
是 throw
语句 ,而不是表达式。因此,编译器将其拒绝为lambda表达式的正文。
您可以下载兔子洞,了解所有类型的表达式,这里(遵循语法)。
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
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).
这篇关于为什么引发运行时异常的Java Lambda需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!