开发者

How to cope with Exceptions in Linq Queries?

I have found using Linq to be a useful experience when querying lists, and provides succinct, readable code.

The issue I have found is when an error occurs it is very hard to debug which part of the query is failing.

Is there a way to find this out? It just highlights the whole query and returns the error.

An example is if I have a list:

class Person
{
    p开发者_JAVA百科ublic IList<string> Pets
    {
        // please, don't do this at home :)
        get { throw new InvalidOperationException(); }
    }
}

Person person = new Person();

List<Person> myStrings = new List<Person>();
myStrings.Add(person);

var people = from p in myStrings
             where p.Pets.Count > 0
             select p;

Obviously checking for null is a simple solution, but for more convoluted errors that also may not be as obvious, how should we locate where in the query is failing?

Is there a Linq profiler or something?


You can set Visual Studio to break on all exceptions, and it will break as soon as the exception is thrown, inside your lambda.

This can also uncover subtle bugs; I highly recommend it.
However, for old, exception-laden code, it will be a nightmare.


Person person = new Person();
person.Pets = null;

List<Person> myStrings = new List<Person>();
myStrings.Add(person);

var people = from p in myStrings
             let pets = p.Pets
             where pets != null && pets.Count > 0
             select p;

I'm sorry if people don't think this is a duplicate. It is.

The problem is always to break down your expression, looking for something that's null that you didn't think about ahead of time. The problem is no different with LINQ queries and lambda expressions as with any other complicated expression. Break it down, put the pieces on separate lines, then find exactly which line it breaks on.


This isn't too hard in Visual Studio 2010:

How to cope with Exceptions in Linq Queries?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜