Checked exceptions thrown from within lambda expressions

前端 未结 2 1399
甜味超标
甜味超标 2020-12-18 04:05

Can you please explain why checked exceptions have to be caught from within lambda expressions? In other words, why does the following code not compile...

pu         


        
2条回答
  •  情书的邮戳
    2020-12-18 04:41

    The issue isn't the lambda expression, it's the interface it's implementing. Remember, a lambda expression is basically just shorthand for an anonymous class that implements a given interface.

    In this case, forEach takes a java.util.function.Consumer:

    public interface Consumer {
        void accept(T t);
        ...
    }
    

    Note that accept is not declared to throw anything. This means that no implementation of it can throw anything; not a named class, not an anonymous class, and not a lambda.

提交回复
热议问题