Rk R Bairi
Rk R Bairi

Reputation: 1369

propagating Exception from inside of a forEach loop

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{

}

I am trying to call getVehicles2() from getVehicles. The compiler complains that there is an unhandled Exception in doing so. Wouldn't declaring the exception with throws is not sufficient to propagate it upto the parent controller method. Try/catch would resolve the error, but I thought declaring throws would propagate relating errors to calling method.

Upvotes: 0

Views: 912

Answers (1)

mrod
mrod

Reputation: 792

Check the signature of the Consumer. If you expand the lambda expression as an anonymous class, you'd get:

new ArrayList<>().forEach(new Consumer<Object>() {
    @Override
    public void accept(Object obj) {
        getVehicles2(req);
    }
}

As you can see, the foreach receives a Consumer, whose accept method does not have the "throws UnsupportedEncodingException" you'd need.

Upvotes: 2

Related Questions