I’m sure we all have received the wonderfully vague ‘Object reference not set to instance of an Object’ exception at some time or another. Identifying the object that is the problem is often a tedious task of setting breakpoints and inspecting all members in each statement.
Does anyone have any tricks to easily and efficiently identify the object that causes the exception, either via programmatical means or otherwise?
–edit
It seems I was vague like the exception =). The point is to _not have to debug the app to find the errant object. The compiler/runtime does know that the object has been allocated/declared, and that the object has not yet been instantiated. Is there a way to extract / identify those details in a caught exception
@ W. Craig Trader
Your explanation that it is a result of a design problem is probably the best answer I could get. I am fairly compulsive with defensive coding and have managed to get rid of most of these errors after fixing my habits over time. The remaining ones just tweak me to no end, and lead me to posting this question to the community.
Thanks for everyone’s suggestions.
At the point where the NRE is thrown, there is no target object — that’s the point of the exception. The most you can hope for is to trap the file and line number where the exception occurred. If you’re having problems identifying which object reference is causing the problem, then you might want to rethink your coding standards, because it sounds like you’re doing too much on one line of code.
A better solution to this sort of problem is Design by Contract, either through builtin language constructs, or via a library. DbC would suggest pre-checking any incoming arguments for a method for out-of-range data (ie: Null) and throwing exceptions because the method won’t work with bad data.
[Edit to match question edit:]
I think the NRE description is misleading you. The problem that the CLR is having is that it was asked to dereference an object reference, when the object reference is Null. Take this example program:
When you run this, it’s going to throw an NRE on line 5, when it tried to evaluate the ToString() method on foo. There are no objects to debug, only an uninitialized object reference (foo). There’s a class and a method, but no object.
Re: Chris Marasti-Georg’s answer:
You should never throw NRE yourself — that’s a system exception with a specific meaning: the CLR (or JVM) has attempted to evaluate an object reference that wasn’t initialized. If you pre-check an object reference, then either throw some sort of invalid argument exception or an application-specific exception, but not NRE, because you’ll only confuse the next programmer who has to maintain your app.