Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to catch exceptions when inside a loop?

HI, I was wondering what your thoughts are on exception handling, i.e I have a method:

public void Method{}
{
   for (int i=0;i < length )
   {
    // dosomething that may case exception
    ...
    ...
    // rest of the code
   }
}

Should I add the try catch block for exception handling for the whole loop or just the code that is most vunerable or something else? What's the best practice?

like image 325
Rubans Avatar asked Aug 11 '10 17:08

Rubans


2 Answers

The answer is on what level you want/can handle it. If processing of one element can fail but you can continue processing then use try catch inside loop. if error can happen and you can't continue then use outer try catch.

like image 145
Andrey Avatar answered Oct 17 '22 15:10

Andrey


It depends on how you want your code to flow.

For example should the loop continue to execute even if one element throws an exception? If so, then you want your try/catch inside the for. If not then you want your try / catch around the for.

like image 2
Brian R. Bondy Avatar answered Oct 17 '22 15:10

Brian R. Bondy