Detecting what the target object is when NullReferenceException is thrown

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:

public class NullPointerExample {
  public static void Main()
    Object foo;
    System.Console.WriteLine( foo.ToString() );

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.

Leave a Comment