Where to catch exceptions when inside a loop?

HI, I was wondering what you think about 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 a catch try block to handle exceptions for the entire loop, or just the code that is most vunerable or something else? What is the best practice?

+5
source share
6 answers

The answer is at what level you want / can handle. If processing one item may fail, but you can continue processing, use the try catch loop inside. if an error can occur and you cannot continue using an external try catch.

+9
source

, , .

, , ? , , try/catch for. , , try/catch .

+2

.

, - ? .

, , Exception? .

+1

, , . . . YMMV

0

, .

if you plan to continue the iteration when some kind of exception occurs, naturally you insert a catch try block.

if you want to stop the operation when some kind of error occurs best, you need to put catch try in the 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.

0
source

The fewer lines you can call problematic, the better. Then you should put them in a catch try block.

0
source

All Articles