If an Exception is thrown in a List<T>.ForEach, does the iteration stop?

c#, exception, foreach

Solution

Yes, if an exception is thrown, the loop exits. If you don't want that behaviour, you should put exception handling into your delegate. You could easily create a wrapper method for this:

public static Action<T> SuppressExceptions<T>(Action<T> action)
{
    return item =>
    {
        try
        {
            action(item);
        }
        catch (Exception e)
        {
            // Log it, presumably
        }
    };
}

To be honest, I would try to avoid this if possible. It's unpleasant to catch all exceptions like that. It also doesn't record the items that failed, or the exceptions etc. You really need to think about your requirements in more detail:

- Do you need to collect the failed items?

- Do you need to collect the exceptions?

- Which exceptions do you want to catch?

It would almost certainly be cleaner to create a separate method which used the normal `foreach` loop instead, handling errors and collecting errors as it went. Personally I generally prefer using `foreach` over `ForEach` - you may wish to read Eric Lippert's thoughts on this too.

Problem

If I have the following code: ``` List<MyClass> list = GetList(); list.ForEach(i => i.SomeMethod()); ``` and let's say `SomeMethod()` throws an exception. Does `ForEach` continue iterating, or does it just stop right there? If it does terminate, is there any way to get the rest of the items in the collection to run their methods?

Original source