2

In my code, I have a loop and inside a try catch. When an error is encountered, catch block works, should log the error and send an email to inform about the error message.

Now I want it to do this and go back to the loop to continue the treatement.

If I have to loop through 100 records, and an error is detected in the 51st record, then the catch should log it, email it, and come back to continue with the 52nd record (kind of RESUME NEXT in VBS).

How can this be done?

4 Answers 4

9

Catch the exception in the loop (not outside the loop). Then it would just continue with the loop.

Sign up to request clarification or add additional context in comments.

4 Comments

aggreed that would be the simplest way
What if he has a logic after the try catch statement still inside the loop ??
@Akram Shahda, what would be wrong with him just including that logic in the try? Even if that section of code won't throw an error, he needs it in the try so that it'll skip that logic.
@Corey Ogburn: It is recommended to place only logic that might throw exceptions inside the try{} catch{} statement. Still he can do whatever he need.
3
foreach(var record in records)
{
   try
   {
       processRecord(record);
   }
   catch(*Exception that you are interested in*)
   {
       // log exception
       // spawn new backgroundworker to send email about exception
   }

}

Comments

1

in my code I have a loop and inside a try catch,

If your try-catch block is inside your loop, then you should be fine:

for ( ... )
{
    try
    {
        ...
    }
    catch (...)
    {
        ...
    }
}

If its outside your for loop, then just move it inside :)

Comments

1

place the following structure within your loop:

//While (Looping)
//{    

    try
    {
        // write your logic here ..

    }
    catch(Exception ex)
    {
        // log exception && send mail

        continue;
    }


    // more logic could be here ..

//}

2 Comments

Thanks alot guys, after 5 hours coding non stop, one start saying posting 6u!! sh!t :)) i was just confused, all solutions worked just fine thanks
@evdotnet: We are glad to help. However, would you thank us by accepting the most appropriate answer ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.