views:

96

answers:

6

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?

A: 

My preference is to keep the exception handling as close to the code that throws the exception as possible. This gives you the best stack trace. I would put it inside the loop. YMMV

sidewaysmilk
Usually, where the exception happens _isn't_ where your program is ready to deal with it.
Pedro d'Aquino
A: 

That depend of what are You doing

if You plan to continue the iteration when some exception raise, naturally You put the try catch block into for.

if You want to stop the operation when some error occur better way is to put for into try catch block.

for (int i = 0; i < 10000000; i++) {
        try {

        }catch (Exception e) {

        }
    }

Duration 16 ms.

   try {
        for (int i = 0; i < 10000000; i++) {

        }
    }catch (Exception e) {

    }

Duration 0ms.

Vash
+1  A: 

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.

Brian R. Bondy
+7  A: 

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.

Andrey
A: 

The less lines you can identify as problematic, the better. Then you should place these inside the try catch block.

Eton B.
+1  A: 

That depends.

Do you want to continue processing elements if you hit an Exception on any single element? Then handle the Exception inside the loop.

Do you want loop processing to stop if an Exception is hit? Then handle the Exception outside the loop.

Justin Niessner