Checked exceptions thrown from within lambda expressions

前端 未结 2 1393
甜味超标
甜味超标 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:30

    It seems that your read method throws IOException.

    The signature of IntStream.forEach is forEach(IntConsumer action), where IntConsumer has a void accept(int value) method. In that context your lambda expression i -> someList.add(read(istream)) is equivalent to:

    public class IntConsumerImplementation implements IntConsumer {
       ObjectInputStream istream;
       public void accept(int i) {
          someList.add(read(istream));
       };
    }
    

    which doesn't compile because read throws a checked exception.

    On the other hand, lambda expressions may throw checked exceptions if the functional interface defines them (which is not the case for consumers or other java.util functional interfaces).

    Suppose the following made up example:

     @FunctionalInterface
     public interface NotAnIntConsumer {
        public void accept(int i) throws IOException;
     }
    

    Now the following compiles:

    forEach(NotAnIntConsumer naic) { ... }
    doSomething(ObjectInputStream istream) throws IOException {
       IntStream.range(0, 10).forEach(i -> someList.add(read(istream)));
    }
    

提交回复
热议问题