Why must throw statements be enclosed with a full code block in a lambda body?

前端 未结 3 654
清歌不尽
清歌不尽 2021-01-03 17:36

If there is a single statement in a lambda function, we can omit defining the full code block for it:

new Thread(() -> System.out.println());
3条回答
  •  情深已故
    2021-01-03 18:28

    In Java8, the grammar of a lambda body only accepts an expression or a block. Whereas throwing an exception is a statement, not an expression.

    throwStatement: 'throw' expression ';' ;
    
    lambdaBody: expression | block;
    
    expression: lambdaExpression | assignmentExpression;
    
    block : '{' blockStatements? '}' ;
    

    Maybe it can be enhanced by including throwStatement into lambdaBody in the next jdk version if it is needed. Indeed, we need that as you mentioned above. for example:

    lambdaBody: expression | block | throwStatement;
    

提交回复
热议问题