javaexceptionerror-handlingforeachthrow

Why am I only getting an Unhandled Exception Type error only when using List.forEach?


I have some method that throws an exception:

public void myMethod(MyBean bean) throws SomeException {
    ...
}

And another method is calling this method like this with no errors/warnings from Eclipse:

public void processBeanList(List<MyBean> myBeanList) {
    for (int i = 0; i < myBeanList.size(); i++) {
        MyBean myBean = myBeanList.get(i);
        myMethod(myBean);
    }
}

However if I change the implementation of this processBeanList to the following, I get an "Unhandled exception type SomeException" error:

public void processBeanList(List<MyBean> myBeanList) {
    myBeanList.forEach(myBean -> {
        myMethod(myBean); // Eclipse underlines this, mentions error
    });
}

I realize that if the method throws the Exception then it should be handled or re-thrown, but is there something different between these two implementations that I'm missing, which would lead Eclipse to show the error in once case and not the other? Or is this just something that Eclipse, for whatever reason, is picking up in the second instance, but not in the first when it should be picked up in both cases?


Solution

  • Because the parameter of forEach(...) is a Consumer.

    myBean -> {
      myMethod(myBean);
    }
    

    The above is an implementation of consumer as lambda function.

    Consumer.accept() does not throw exceptions, so you have to handle it in some way - possibly catch and rethrow as unchecked exception.