Skip to content

Instantly share code, notes, and snippets.

@jamescrowley
Created October 30, 2014 08:33
Show Gist options
  • Save jamescrowley/802cbec1594b6b31b3af to your computer and use it in GitHub Desktop.
Save jamescrowley/802cbec1594b6b31b3af to your computer and use it in GitHub Desktop.
Passes in C# fails in Mono - looks like different behaviour in Linq rather than Iterator blocks
public static IEnumerable<T> HandleExceptions<T>(this IEnumerable<T> values, Func<Exception, T> onException)
{
using (var enumerator = values.GetEnumerator())
{
bool next = true;
Exception lastException = null;
while (next)
{
try
{
next = enumerator.MoveNext();
}
catch (Exception ex)
{
lastException = ex;
}
if (lastException != null)
{
yield return onException(lastException);
lastException = null;
}
else if (next)
{
yield return enumerator.Current;
}
}
}
}
[Test]
public void HandleExceptions()
{
IList<Exception> exceptions = new List<Exception>();
Func<Exception, int?> callback = (ex) => { exceptions.Add(ex); return (int?)0; };
var result = Enumerable.Range(0, 5).Select(x => {
if (x%2 == 0)
throw new Exception("Exception" + x);
return (int?)x;
}).HandleExceptions(callback).ToList();
Assert.AreEqual(5,result.Count);
Assert.AreEqual(3,exceptions.Count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment