Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why doesn't .NET give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

Update: The exception The system cannot find the file specified has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist. instead of that general message? As a developer, I vote yes.

share|improve this question
13  
The exception should include a stack trace with line number. I would start my investigation from there looking at every object accessed on that line. –  PersonalNexus Jan 15 '12 at 11:25
1  
Also, I've always wondered why the exception helper dialog in Visual Studio includes the "helpful" hint to use new to create instances of a class. When does such a hint every really help? –  PersonalNexus Jan 15 '12 at 11:27
1  
If you have a chain of ten object calls then you've got a problem with coupling in your design. –  Pete Kirkham Feb 11 '13 at 9:32
3  
see this question stackoverflow.com/questions/14787580/… –  please delete me Feb 12 '13 at 8:15
4  
I love how every single answer to this question are along the lines of "Use a debugger, log your errors, check for null, it's your fault anyway" which are not answering the question but putting the blame on you. Only on stackoverflow does someone actually give you an answer (which I think says it's too much overhead for the VM to keep track of). But really, the only people who can answer this question properly is someone from microsoft who worked on the framework. –  LachlanB Feb 20 '13 at 23:19
show 2 more comments

6 Answers 6

up vote 19 down vote accepted

The NullReferenceException basically tells you: you are doing it wrong. Nothing more, nothing less. It's not a full-fledged debugging tool, on the contrary. In this case I'd say you're doing it wrong both because

  • there is a NullReferenceException
  • you didn't prevent it in a way you know why/where it happened
  • and also maybe: a method requiring 20 objects seems a bit off

I'm a big fan of checking everything before things start going wrong, and providing good information to the developer. In short: write checks using ArgumentNullException and the likes and write the name yourself. Here's a sample:

void Method(string a, SomeObject b)
{
    if (a == null) throw ArgumentNullException("a");
    if (b == null) throw ArgumentNullException("b");

    // See how nice this is, and what peace of mind this provides? As long as
    // nothing modifies a or b you can use them here and be 100% sure they're not
    // null. Should they be when entering the method, at least you know which one
    // is null.
    var c = FetchSomeObject();
    if(c == null)
    {
        throw InvalidOperationException("Fetching B failed!!");
    }

    // etc.
}

You could also look into Code Contracts, it has it quirks but it works pretty well and saves you some typing.

share|improve this answer
16  
@SaeedNeamati you are not implying that because you have a large codebase you should not do decent error checking, right? Imo the larger the project, the more important become the roles or error checking and reporting. –  stijn Jan 15 '12 at 12:54
6  
+1 for good advice, even if it doesn't answer the actual question (which probably only Anders Hejlsberg can answer). –  Ross Patterson Jan 15 '12 at 15:09
9  
+1 for excellent advice. @SaeedNeamati you should listen to this advice. Your problem is caused by carelessness and a lack of professionalism in the code. If you don't have time to write good code, you have much bigger problems... –  MattDavey Oct 26 '12 at 9:49
3  
If you don't have time to write good code, then you definitely don't have time to write bad code. Writing bad code takes longer than writing good code. Unless you really don't care about bugs. And if you really don't care about bugs, why write the program at all? –  MarkJ Oct 26 '12 at 12:09
4  
@SaeedNeamati I only say that checking every object to get sure that it's not null, is not a good method Seriously. It's the best method. And not just null, check every argument for reasonable values. The earlier you catch errors, the easier to find the cause. You don't want to have to backtrack several levels in the stack trace to find the causing call. –  jgauffin Oct 26 '12 at 12:25
show 6 more comments

It really should show exactly what you are trying to call. It's like saying "There's a problem. You need to fix it. I know what it is. I'm not going to tell you. You go figure it out" Bit like half the answers on this Stack Overflow, ironically.

So how useful would it be, for example, if you got this...

Object reference (HttpContext.Current) not set to instance of an object

...? To have to go into the code, step through it, and work out that the thing you are trying to call is null is fine, but why not just give us a little helping hand?

I agree that it is usually useful to step through the code to get to the answer (because you will probably find out more), but often a lot of time and frustration would be saved if the NullReferenceException text was more like the example above.

Just sayin.

share|improve this answer
    
How is the runtime supposed to know what is null though? –  Will Feb 1 '13 at 16:27
3  
The runtime has more information than it provides. Whatever useful info it has, it should provide. That's all I'm saying. In response to your question, why doesn't it know? If you know the answer to that you might be able to provide a better comment than you have. –  LiverpoolsNumber9 Feb 11 '13 at 16:55
    
Agreed, and I'd say the same for KeyNotFoundException and many other annoyances... –  sinelaw Mar 19 '13 at 20:33
    
Actually, in the case of null dereferencing this looks like a limitation in the way the CLR dereferences (thanks to Shahrooz Jefri's comment on the OP's question) –  sinelaw Mar 19 '13 at 20:37
add comment

Your log should include a stack trace - that usually gives you a hint as to which line in the method has the problem. You may need to make your release build include PDB symbols so you have an idea which line the error is on.

Granted, it won't help you in this case:

Foo.Bar.Baz.DoSomething()

The tell don't ask principle can help to avoid such code.

As to why the information isn't included, I'm not sure - I suspect that at least in a debug build, if they really wanted to, they could figure it out. Taking a crash dump and opening in WinDBG may help.

share|improve this answer
add comment

Cromulent hit the nail on the head I think, however there is the obvious point too that if you're getting a NullReferenceException you have uninitialised variable(s). The argument that you have circa 20 objects being passed into a method cannot be said to be a mitigation: as the creator of a chunk of code you have to be responsible for its doings, that includes its compliance to the rest of a codebase, as well as proper and correct utilisation of variables etc.

it is onerous, tedious and sometimes dull, but the rewards at the end are worth it: many are the times when I have had to trawl through log files weighing in at several gigabytes, and they are almost always helpful. However before you get to that stage, the debugger can help you, and before that stage good planning will save a lot of pain(and I do not mean a fully engineered approach to you code solution either: simple sketches and some notes can and will be better than nothing).

In regards to the Object reference not set to an instance of an object the code cannot guess at values we may like: that's our job as programmers, and it simply means you have passed an uninitialised variable in.

share|improve this answer
add comment

Build your Project with PDB files. this will help you to discover which line cause an error.(Line Number + Stack Trace).

share|improve this answer
add comment

Learn to use the debugger. This is exactly the kind of thing it is designed for. Set a break point on the method in question and away you go.

Simply step through your code and see exactly what the values of all your variables are at certain points.

Edit: Frankly I'm shocked that no one else has mentioned using the debugger yet.

share|improve this answer
    
So you are saying that all exceptions can easily be reproduced when using a debugger? –  jgauffin Feb 20 '13 at 11:54
    
@jgauffin I'm saying that you can use a debugger to see why an exception is being thrown in real world code rather than synthetic unit tests that might not actually fully test the code in question or the unit tests themselves may have bugs in which causes them to miss bugs in the real code. A debugger trumps just about any other tool I can think of (except perhaps things like Valgrind or DTrace). –  Cromulent Feb 20 '13 at 12:11
    
So you are saying that we always have access to the failing computer and that debugging is better than unit tests? –  jgauffin Feb 20 '13 at 12:17
    
@jgauffin I'm saying if you have a choice then go with the debugger in preference to other tools. Of course if you don't have that choice then it is a bit of a non-starter. Clearly this is not the case with this question which is why I gave the answer I did. If the question had been how do you fix this issue on a clients computer with no way to do remote debugging (or local debugging) my answer would have been different. You seem to be trying to warp my answer in ways which have no relevance to the question at hand. –  Cromulent Feb 20 '13 at 17:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.