Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling within a LINQ Expression

I have a simple LINQ-expression like:

newDocs = (from doc in allDocs
           where GetDocument(doc.Key) != null
           select doc).ToList();

The problem is, GetDocument() could throw an exception. How can I ignore all doc-elements where GetDocument(doc.Key) == null or throws an exception?

The same code in old school looks like:

foreach (var doc in allDocs)
{
    try
    {
        if (GetDocument(doc.Key) != null) newDocs.Add(doc);
    }
    catch (Exception)
    {
        //Do nothing...
    }
}
like image 204
Rocco Hundertmark Avatar asked Dec 01 '10 08:12

Rocco Hundertmark


2 Answers

allDocs.Where(doc => {
    try {
        return GetDocument(doc.Key) != null;
    } catch {
        return false;
    }
}).ToList();

I'm not sure it's possible using query comprehension syntax, except via some baroque atrocity like this:

newDocs = (from doc in allDocs
           where ((Predicate<Document>)(doc_ => {
               try {
                   return GetDocument(doc_.Key) != null;
               } catch {
                   return false;
               }
           }))(doc)
           select doc).ToList();
like image 137
Marcelo Cantos Avatar answered Oct 21 '22 19:10

Marcelo Cantos


A linq extension can be written to skip all elements that cause an exception. See this stackoverflow post

 public static IEnumerable<T> CatchExceptions<T> (this IEnumerable<T> src, Action<Exception> action = null) {
        using (var enumerator = src.GetEnumerator()) {
            bool next = true;

            while (next) {
                try {
                    next = enumerator.MoveNext();
                } catch (Exception ex) {
                    if (action != null) {
                        action(ex);
                    }
                    continue;
                }

                if (next) {
                    yield return enumerator.Current;
                }
            }
        }
    }

Example:

ienumerable.Select(e => e.something).CatchExceptions().ToArray()

ienumerable.Select(e => e.something).CatchExceptions((ex) => Logger.Log(ex, "something failed")).ToArray()

posting this here in case anyone else finds this answer first.

like image 36
katbyte Avatar answered Oct 21 '22 19:10

katbyte