从forEach循环内部传播异常
问题描述:
public controllerMethod() throws UnsupportedEncodingException {
getVehicles(req);
}
public List<vehicles> getVehicles(A req) throws UnsupportedEncodingException{
someObject.forEach(obj -> {
getVehicles2(req); //try catch resolves but why wouldn't throws handle this ?
}
}
public getVehicles2(A req) throws UnsupportedEncodingException{
}
我试图从getVehicles中调用getVehicles2()。编译器抱怨说这样做有一个未处理的异常。不会用throws声明异常不足以将其传播到父控制器方法。 try/catch语句就解决了错误,但我想声明抛出将传播有关错误调用方法。从forEach循环内部传播异常
答
检查消费者的签名。如果展开lambda表达式作为一个匿名类,你会得到:
new ArrayList<>().forEach(new Consumer<Object>() {
@Override
public void accept(Object obj) {
getVehicles2(req);
}
}
正如你所看到的,的foreach收到消费者,其接受方法不具有“抛出UnsupportedEncodingException “你需要。
它看起来好像没什么问题;编译器不应该抱怨。 – mrod
@mrod对不起改变的问题。该电话是foreach循环里面,这就是为什么它migth不投在上面工作 –