Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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());

Why is that not the case for statements that throw exceptions? This yields a compilation error stating '{' expected:

new Thread(() -> throw new RuntimeException());

Of course, enclosing the lambda body in a code block works:

new Thread(() -> {
    throw new RuntimeException();
});
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

AFAIK The jls says that the lambda body has to be:

expression or a block. Having it like this:

new Thread(() -> throw new RuntimeException());

is neither and the compiler somehow informs you about that.

Declaring it like this:

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

makes it a block. Here is the relevant part:

A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.

about 4 years ago · Santiago Trujillo Denunciar

0

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;
about 4 years ago · Santiago Trujillo Denunciar

0

A throw statement is, well, a statement and not an expression so it must be placed within braces. According to this article, the Java Expert Group had an informal survey on the syntax of lambdas at the time, and there were four options:

  • Strawman: #(arglist)(expr) and #(arglist){statements}
  • BGGA: { args -> statements } (similar to Scala and Groovy)
  • SotL: #{ args -> statements}
  • Redmond: (args) -> { statements }

Ultimately, the choice was to adopt a syntax similar to that of C# according to this thread, which also looks closest to the last option above as far as I can see. In C#, there is a distinction between expression lambdas and statement lambdas:

Expression lambda (C#):

(input parameters) => expression

Statement lambda (C#):

(input parameters) => {statement;}  

The syntax is explained in this MSDN documentation page.

And the rationale for choosing this syntax over the other options is mentioned in the previous thread:

The decision to choose this syntax was twofold:

  • The syntax scores "pretty well" on most subjective measures (though has cases where it looks bad, just like all the others do). In particular, it does well with "small" lambdas that are used as method arguments (a common case), and also does well with large (multi-statement) lambdas.

  • Despite extensive searching, there was no clear winner among the alternatives (each form had some good aspects and some really not very good aspects, and there was no form that was clearly better than the others). So, we felt that it was better to choose something that has already been shown to work well in the two languages that are most like Java -- C# and Scala -- rather than to invent something new.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda