using System.Collections.Generic;
public static class Program
static IEnumerable<int> TestCases3(Action<int, Exception> exceptionHandler = null)
foreach (var item in Enumerable.Range(0, 10))
int value = default(int);
throw new ApplicationException("This bit failed");
if (exceptionHandler != null)
exceptionHandler(item, e);
public static IEnumerable<T> CatchExceptions<T>(this IEnumerable<T> src, Action<Exception> action = null)
using (var enumerator = src.GetEnumerator())
next = enumerator.MoveNext();
yield return enumerator.Current;
public static void Main()
Console.WriteLine(string.Join(", ", Enumerable.Range(-1, 10).Select(v => 1 / v).CatchExceptions().ToArray()));
Console.WriteLine(string.Join(", ", TestCases3().Select(v => 1 / v).CatchExceptions().ToArray()));
Console.WriteLine(string.Join(", ", TestCases3().CatchExceptions((e) => Console.WriteLine("Caught: {0}", e.Message)).ToArray()));
Console.WriteLine(string.Join(", ", TestCases3((i, e) => Console.WriteLine("Handled: {0}", e.Message)).CatchExceptions((e) => Console.WriteLine("Caught: {0}", e.Message)).ToArray()));
Console.WriteLine(string.Join(", ", Enumerable.Range(-1, 10).Select(x =>
throw new ApplicationException("Odd Numbers not allowed");
).Select(v => 1 / v).CatchExceptions().ToArray()));