Java 8: How do I work with exception throwing methods in streams?

Suppose I have a class and a method

class A {
  void foo() throws Exception() {
    ...
  }
}

Now I would like to call foo for each instance of A delivered by a stream like:

void bar() throws Exception {
  Stream<A> as = ...
  as.forEach(a -> a.foo());
}

Question: How do I properly handle the exception? The code does not compile on my machine because I do not handle the possible exceptions that can be thrown by foo(). The throws Exception of bar seems to be useless here. Why is that?

7 Answers
7

Leave a Comment