using System.Collections.Generic;
public static class Extensions
public static IEnumerable<T> IgnoreExceptions<T>(this IEnumerable<T> coll) {
return IgnoreExceptions<T, Exception>(coll, _ => { });
public static IEnumerable<T> IgnoreExceptions<T>(this IEnumerable<T> coll, Action<Exception> handler) {
return IgnoreExceptions<T, Exception>(coll, handler);
public static IEnumerable<T> IgnoreExceptions<T, K>(this IEnumerable<T> coll) where K : Exception {
return IgnoreExceptions<T, K>(coll, _ => { });
public static IEnumerable<T> IgnoreExceptions<T, K>(this IEnumerable<T> coll, Action<K> handler) where K : Exception {
using (var en = coll.GetEnumerator()) {
public static void Main()
var coll = Enumerable.Range(1, 50).Select(_ => 2 / r.Next(-5, 5))
.IgnoreExceptions<int, DivideByZeroException>(ex => Console.WriteLine("ex: " + ex.Message));