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

前端 未结 3 633
清歌不尽
清歌不尽 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:31

    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.

提交回复
热议问题