Reputation:
I need a for loop which will complete all its Iterations even if there's any exception in any one of the iterations.
Upvotes: 15
Views: 40264
Reputation: 1
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.
Upvotes: 0
Reputation: 6192
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.
Upvotes: -3
Reputation: 19407
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.
Upvotes: 0
Reputation: 1717
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 { }
}
}
Upvotes: 4
Reputation: 17645
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!
Upvotes: 0
Reputation: 23531
for (...)
{
try
{
// Do stuff
}
catch (Exception ex)
{
// Handle (or ignore) the exception
}
}
Upvotes: 37
Reputation: 4087
Just put each iteration inside a try..catch
foreach(Person a in people)
{
try
{
WorkOnPerson(a);
}
catch
{
// do something if you want to.
}
}
Upvotes: 10