英文:
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 an 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 one 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?
英文:
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?
答案1
得分: 1
因为 forEach(...) 的参数是一个 Consumer。
myBean -> {
myMethod(myBean);
}
以上是将 Consumer 作为 Lambda 函数实现的示例。
Consumer.accept()
不会抛出异常,因此您需要以某种方式处理它,可能是捕获并重新抛出为未检查异常。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论