Russell
Russell

Reputation: 17719

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
{
    public 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?

Upvotes: 1

Views: 2121

Answers (2)

John Saunders
John Saunders

Reputation: 161783

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:

enter image description here

Upvotes: -1

SLaks
SLaks

Reputation: 887459

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.

Upvotes: 4

Related Questions