0

I have two functions throwing Exception:

public void foo() throws Exception {
  // something
}
public void bar() throws Exception {
  // something
}

If I combine those function calls using curly braces in lambda expression, it needs try/catch to handle exception.

public void someFunction() throws Exception {
  someList.forEach(e -> {
    // Show compile error and need try/catch
    foo();
    bar();
  });
}

However, if I combine in for-loop, it is fine.

public void someFunction() throws Exception {
  for (SomeElement e : someList) {
    foo();
    bar();
  }
}

I though try/catch needed because of new closure created (using bracket), but in for-loop, it does not require. I solved it by just using for loop, but I wonder why it happens.

Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
osflw
  • 79
  • 1
  • 8

1 Answers1

2

List#forEach expects a Consumer.

Consumer is a (single-abstract-method) interface that looks like this (simplified):

@FunctionalInterface
public interface Consumer<T>{
    void accept(T t);
}

As you see, accept does not throw any checked exceptions.

The lambda expression is an implementation of that interface so it cannot throw any exceptions, no matter what the other code does.

dan1st
  • 12,568
  • 8
  • 34
  • 67