为什么抛出运行时异常的 Java Lambda 需要括号? [英] Why does a Java Lambda which throws a Runtime Exception require brackets?

查看:17
本文介绍了为什么抛出运行时异常的 Java Lambda 需要括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道java中的lambda不能抛出checked异常,但是可以抛出RuntimeException,但是为什么下面的代码需要括号?

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");});

你为什么不能拥有?

m.computeIfAbsent("", s -> throw new IllegalArgumentException("fail"));

是不是因为编译器假设在这个实例中它会返回一个int,因此即使抛出异常也不能返回?

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?

推荐答案

Java 语言规范 描述 lambda 表达式的主体

lambda 主体可以是单个表达式或块(第 14.2 节).

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

然而,这个

throw new IllegalArgumentException("fail")

throw statement,不是表达式.因此,编译器拒绝将其作为 lambda 表达式的主体.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆