tags:

views:

1479

answers:

7

I need a for loop which will complete all its Iterations even if there's any exception in any one of the iterations.

+7  A: 

Just put each iteration inside a try..catch

foreach(Person a in people)
{
      try
      {
              WorkOnPerson(a);
      }
      catch
      {
              // do something if you want to.
       }
}
RM
+20  A: 
for (...)
{
    try
    {
        // Do stuff
    }
    catch (Exception ex)
    {
        // Handle (or ignore) the exception
    }
}
teedyay
Performance tip, place your declarations outside the for loop.
freggel
@freggel: haha, same tip I wanted to give. But this is the best solution.
Sem Dendoncker
Tip: please use a more tightly defined Exception then Exception say ApplicationException. one big issue with catching exception is ThreadAbortException would be caught here, do you really want to stop the application from stopping here? how about catching a OutOfMemoryException?
David Waters
at worst you could for(...){try{...}catch(SystemException se){LogAndExit(se);}catch(Exception ex){Log(ex);}}
David Waters
ThreadAbortExceptions behave differently to other exceptions so this won't be a problem: http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx But yes, I agree it's best to be as specific as possible in what you catch.
teedyay
@David: `ApplicationException` is now deprecated.
John Saunders
A: 

There is no inbuilt feature in a loop to do that. That is no language feature built in C# that will automatically handle an exception and continue with a loop.

Also to the extent possible, please avoid putting try-catch blocks inside the loop. Even though it solves the problem you mention, consider that the compiler & run-time have to do that much additional job. If there were no exceptions occurring all that would go waste.

Instead let the exceptions be exceptions. That is something that occurs exceptionally: outside your designed input considerations. Of course, this is only a suggestion, if you really have to continue the loop, go with the two options suggested above.

Sesh
No inbuilt feature? What about, say, CATCH?
Matt Olenik
Do or do not. There is no try. ,-)
Rytmis
Oh Man! the stuff is obviously not clear. I am editing it.
Sesh
I gave you a +1. Because I think I understood that you wanted pointed out, that if during "a iteration" an exception occurs and you catch it, the "iteration" itself is "broken". So you can guarantee that in all cases the "action" is done. (Hard to describe this in words...)
TomTom
@TomTom - thanks. that is what I meant. I am editing for more clarity :(
Sesh
There's no performance overhead on try-catch if no exception is thrown. http://msmvps.com/blogs/peterritchie/archive/2007/06/22/performance-implications-of-try-catch-finally.aspx
teedyay
A: 

Well the thing is ... Your solution will have to include a for loop and some sort of error/exception handling process, so you will probably have to embed a try catch statement in your for loop.

If an exception is thrown, there is no way you will complete that one iteration as you would if the exception wasn't thrown. However by using an try catch you can make sure that your loop executes all those iterations that don't throw exceptions.

If you need help with embedding exception handling in a for loop, just use the example posted by teedyay!

Rekreativc
+2  A: 

Or, if this is a recurring pattern in your program, and you're taking the risk for this catch all exception style, wrap it as an extension to your collections. Applying it to the previous example:

people.ForEachIgnorant(ofThrowingWorkOnPerson);

Or:

people.ForEachIgnorant(p => WorkOnPersonThatThrows(p));

Implementation:

public static void IgnorantForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (var item in source)
    {
        try
        {
            action(item);
        }
        catch { }
    }
}
robi
A: 

I think it's also worth noting that if you are using a generic List - you could use the following to iterate the collection:

ForEach(Action action)

http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx

    EmployeesList.ForEach(ProcessEmployee);

    void ProcessEmployee(Employee employeeItem)
    {
        try
        {
            ...
        }
        catch { }
    }

This has the benefit of making the code in your loop reusable.

Peanut
A: 

Do you know what the exception is and what will cause it? Can you test for it and prevent it being thrown, ie. CanCompleteStep or TryCompleteStep. if you cant complete just skip that step. You can then put exception handling out of the loop.

kmo