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 声明异常不足以将其传播到父 Controller 方法。 Try/catch 可以解决该错误,但我认为声明 throws 会将相关错误传播到调用方法。
最佳答案
检查消费者的签名。如果将 lambda 表达式扩展为匿名类,您将得到:
new ArrayList<>().forEach(new Consumer<Object>() {
@Override
public void accept(Object obj) {
getVehicles2(req);
}
}
如您所见,foreach 接收一个 Consumer,其 accept 方法没有您需要的“抛出 UnsupportedEncodingException” .
关于java - 从 forEach 循环内部传播异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45618230/