I need a for loop which will complete all its Iterations even if there's any exception in any one of the iterations.
-
This sounds like an old shoe vs. glass bottle question: http://tinyurl.com/shoevbottle. You might want to provide a lot more details in order to get better solutions including ideas you haven't considered yet. – Wedge Feb 19 '09 at 07:37
-
Wedge, I agree... if you must put a try/catch inside a for loop, like below, then something maybe wrong with the solution. – Chuck Conway Feb 19 '09 at 09:21
-
@Wedge: Excellent metaphor, another bookmark for me, thanks – Binary Worrier Feb 19 '09 at 09:36
7 Answers
for (...)
{
try
{
// Do stuff
}
catch (Exception ex)
{
// Handle (or ignore) the exception
}
}

- 23,293
- 19
- 66
- 73
-
1
-
@freggel: haha, same tip I wanted to give. But this is the best solution. – user29964 Feb 19 '09 at 08:19
-
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 Feb 19 '09 at 09:26
-
at worst you could for(...) { try{...} catch(SystemException se){LogAndExit(se);} catch(Exception ex){Log(ex);} } – David Waters Feb 19 '09 at 09:28
-
1ThreadAbortExceptions 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 Mar 20 '09 at 14:36
-
-
1totaly out of qualify! exceptions must have collected with queue and at the end of loop, check any exception collected by queue if there is some exception must build AggregateException and throw them. http://msdn.microsoft.com/en-us/library/system.aggregateexception.aspx – Nuri YILMAZ Sep 17 '12 at 11:27
Just put each iteration inside a try..catch
foreach(Person a in people)
{
try
{
WorkOnPerson(a);
}
catch
{
// do something if you want to.
}
}

- 4,047
- 2
- 25
- 33
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 { }
}
}

- 1,687
- 16
- 25
-
Better yet, add an argument of type `Action
` and invoke it in the catch block. This way the caller can determine how it's handled and you're not swallowing exceptions. – Aaron Jun 17 '13 at 16:24
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.

- 1
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!

- 16,887
- 18
- 67
- 98
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.

- 18,967
- 20
- 72
- 78
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.

- 5,993
- 4
- 30
- 39
-
-
2
-
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 Feb 19 '09 at 10:00
-
-
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 Feb 19 '09 at 16:58