+ Start a Discussion
Raj R.Raj R. 

Is it good idea to have try-catch in for loop for http requests?

Hi,

We have a need to keep sending HttpRequests to a particular endpoint until the server responds with a particular status code or if the endpoint is not available at all. We were thinking we can complish this by either doing a for loop or a do-while loop. When we make the HttpRequest we wanted to ensure that is done in a try-catch statement so that we can capture any callout exceptions appropriately. 

Would it be advisable to do a try-catch in a for or do-while loop? I have yet to see any performance degradations but just wanted to be sure. 

For loop example
//for loop
for() {
       try {
             HttpRequest request = new HttpRequest();
             //build request by setting headers
             HttpResponse response = http.send(request);
       catch(CallOutException callOutEx) {
            //handle exception
       }
}//end for

Do-while example:
do{
       try {
             HttpRequest request = new HttpRequest();
             //build request by setting headers
             HttpResponse response = http.send(request);
       catch(CallOutException callOutEx) {
            //handle exception
       }
}while(response.getStatusCode() == 200);