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

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

问题描述

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

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

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