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