views:

332

answers:

2
try
{
     list = from XElement e in d.Descendants(wix + "File")
            where e.Attribute("Name").Value.Contains(temp.Name) &&
            e.Parent.Parent.Attribute("Name").Value.Contains(temp.Directory.Name)
            select e;
}
catch (NullReferenceException e)
{
     MessageBox.Show(e.Message);
}
catch (Exception e)
{
     MessageBox.Show(e.Message);
}

now my question is why does this code produce a run time error saying I have a NullReferenceException unhandled. If you need more information about the program let me know.

EDIT: The debugger points to the "where" part of the linq statement. When I run this program direct from the exe file I still get the exception.

A: 

Are you sure that it is this particular block of code that is producing the exception? Have you edited the code in any way before posting it?

David M
When I run this chunk of code in the debugger it points directly to the "where" part of the linq statement.
Adkins
+4  A: 

EDIT: Okay, I think I know the problem... it's due to deferred query execution.

If you've just got the query construction in the try/catch block, that's not going to catch exceptions which occur while the query is being executed.

Look at the stack trace you've got, and you'll find that there'll be a stack frame where you're executing the query - it's just the auto-generated lambda expression which comes from this bit of code, and it's not running within the scope of the try/catch block.

ORIGINAL ANSWER:

Are you just seeing the exception in the debugger? If so, go into the debugger exception dialog and change the preferences for the point at which exceptions cause the debugger to "break". The catch block should be handling the NullReferenceException normally. (Admittedly I don't think you should really be catching NullReferenceException in the first place, and catching all exceptions like that is generally a bad idea too, other than at the top of the stack - but that's a different matter.)

Jon Skeet
The debugger points me to the "where" part of the linq statement. When I run this program normally (aka no debugger, just straight run) I still get the exception. Also just for the record I normally wouldn't be catching all exceptions like that either, but I have been trying to figure out why the more specialized exception wasn't working.
Adkins
@Adkins: Okay, I've worked it out now - see my edit.
Jon Skeet
@Adkins: Move the catch block to where it's *actually* executing... or call `ToList()` to execute the query eagerly and remember the results.
Jon Skeet
@Jon: Thanks a lot. I have been staring at that little bit of code for far too long. I added a foreach that actually worked with the code into the try block and now it works perfectly!
Adkins