单行Lambda和运行时异常 - 不编译? [英] Single line Lambda and Run-time exceptions - Not compiling?

查看:250
本文介绍了单行Lambda和运行时异常 - 不编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理单行lambda和运行时异常。

I am working on single line lambda and run time exceptions.

我测试了以下用例并找到了声明 1 未编译声明 2 编制正常的地方。

I have tested following use cases and found statement 1 is not compiling where as statement 2 is compiling fine.

 new Thread(() -> throw new RuntimeException("test")); // 1
 new Thread(() -> new RuntimeException("test")); //2

请帮助我理解为什么声明1没有编译但声明二编译正常。

Please help me understand why statement 1 is not compiling but statement two is compiling fine.

推荐答案

定义了lambda表达式(在 JLS 15.27.Lambda表达式):

A lambda expression is defined (in JLS 15.27. Lambda Expressions ) as:


LambdaExpression

LambdaParameters - > LambdaBody

LambdaExpression:
LambdaParameters -> LambdaBody

A LambdaBody定义为:

A LambdaBody is defined as:


LambdaBody

表达式

Block

LambdaBody:
Expression
Block

在两个lambda表达式中,你不使用块作为lambda体(需要花括号),这意味着你必须使用表达式。

In both your lambda expressions, you don't use a block as the lambda body (that would require curly braces), which means you must be using an Expression.

表达式定义为:


表达式可以大致分为以下之一g句法形式:

Expressions can be broadly categorized into one of the following syntactic forms:


  • 表达式名称(§6.5.6)

  • Expression names (§6.5.6)

主要表达式(§15.8 - §15.13)

Primary expressions (§15.8 - §15.13)

一元运算符表达式(§15.14 - §15.16)

Unary operator expressions (§15.14 - §15.16)

二元运算符表达式(§15.17 - §15.24和§15.26)

Binary operator expressions (§15.17 - §15.24, and §15.26)

三元运算符表达式(§15.25)

Ternary operator expressions (§15.25)

Lambda表达式(§15.27)

Lambda expressions (§15.27)

new RuntimeException(test)属于主要表达式类别,其中包括对象创建(正在创建对象的事实)是异常没有区别)。因此它是一个有效的lambda体。

new RuntimeException("test") falls into the category of "Primary expressions", which includes object creations (the fact that the object being created is an Exception makes no difference). Therefore it's a valid lambda body.

另一方面,抛出新的RuntimeException(test) doesn' t属于这些类别中的任何一个,因此不是表达式。

On the other hand, throw new RuntimeException("test") doesn't fall into any of these categories, and therefore is not an expression.

为了使lambda主体包含该语句,您必须使用Block LambdaBody:

In order for a lambda body to contain that statement, you must use a Block LambdaBody:

new Thread(() -> {throw new RuntimeException("test");});

这篇关于单行Lambda和运行时异常 - 不编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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