简体   繁体   中英

Source of System.NullReferenceException

I am implementing a error logger for a web shop and just logging a NullReferenceException in a specific class is only useful to a certain level. I am not really interested in how to prevent the exception, as I am aware of that, but sometimes it still happens thus the error logger.

Then the question is: How do I find the source of a System.NullReferenceException inside all the exception information.

Make sure you log the full stack trace. Assuming you've got debug information turned on (no reason not to for a web app...) you should be able to get to the line which caused the problem.

Of course, that won't always give you all the information you need, if you've got:

if (foo.Bar.Baz && person.Address.Road.Length)

in a single line... but it's the best starting point you'll get.

Additionally, adding argument validation to methods can make it a lot simpler to pin down what's wrong. Personally I'm a fan of helper methods for this. For example, in Noda Time we have Preconditions , so I can just call:

Preconditions.CheckNotNull(foo, "foo");

(which also returns the value of foo , which is handy in constructors which are copying arguments into fields).

The earlier you can detect the unexpectedly-null reference, the better.

If I understand the question correctly, in Visual Studio, go to Debug > Exceptions, and check all options to throw exceptions. This will allow you to see everything that is being thrown while debugging. You can possibly use the contents of InnerException to determine what the root location of the error is being caused.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM