Unhandled exception in try-catch

回眸只為那壹抹淺笑 提交于 2019-12-08 11:59:03

问题


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.


回答1:


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.)



来源:https://stackoverflow.com/questions/1998566/unhandled-exception-in-try-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!