Object Reference Not Set to an Instance of an Object

I gotta tell you, if there is one killer exception message that n00b programmers bitch about, that's the one. And 99 percent of the time, the real problem is what's between the keyboard and the chair!

Look, if you get this message it means you tried to use an object variable that's null. If it's null, that's either because you have a coding logic error that's allowing it to come back null, or some condition that you didn't forsee brought it back null and you didn't have defensive code to check for this. If it legitimately can come back in a state of Nothingness, then you need to test for that and code the rest of your logic accordingly. You CANNOT assume!

Wanna know something else? Out of those 99 percent, a similar percentage of programmers have not taken the time to wrap their code logic in a Try / Catch or Try / Catch / Finally block.

If they did, they wouldn't be posting inane questions to forums and newsgroups about it! It's OK if you are like totally new and this is the first time. But if you are the kind of person who cannot learn the lessons of history, I don't feel sorry for you being doomed to repeat it.

Look, here's the pattern. It doesn't matter whether its VB.NET, C#, whatever:

Try
' Your potentially buggy code here
Catch ex as Exception
' put a breakpoint on the next line so you can see what happened, D00d!
System.Diagnostics.Debug.WriteLine (ex.Message & ex.StackTrace)
End Try

Do this with ALL of your code. Learn to wipe your own butt. You will thank me later.

Your Mantra is: trycatch, and if you do this again I'm gonna send Chuck Norris out to fix your fyookin' computer, OK?

N.B. The post isn't even 4 hours old, and already I'm getting flamed by comments about not illustrating catching for the specific exception type. Look, we are dealing with a post oriented at complete n00bs who need to learn what an exception is first. Nobody is pontificating here - I was one of those, once. Then we can get to the next level. My point is that learning to catch and examine exceptions is a useful debugging tool as well as being a valid programming construct. The comments are, of course, right on the money, but my fear is that they will take us off the primary topic, which is - learn how to debug your own code!

Comments

  1. Anonymous3:15 PM

    Wait, you yell at people to not use null references and catch exceptions...and you give the advice to catch the base Exception type?!

    Ugh.

    ReplyDelete
  2. I don't beleive that you recommend to solve "Object Reference Not Set to an Instance of an Object" problem by using try/catch block!
    What's worse -- you recommend to catch System.Exception.

    Proper approach, is to test if the value is null and throw your own exception.
    Something like this:

    if (myObject == null)
    {
    throw new System.ArgumentNullException("myObject");
    }
    myObject.ExecuteMyMethodOrGetProperty();


    Such code will explode as well, but that would be easily identifiable explosion.

    ReplyDelete
  3. Anonymous5:51 AM

    This was really stupid, please remove this post unless you really want to cause harm to the so-called n00bs. Objects should be checked for null, and a MEANINGFUL exception should be thrown - NEVER, EVER, EVER a generic Exception. You are a fraud.

    ReplyDelete
  4. "This was really stupid": What is this text, "didn't have defensive code to check for this. If it legitimately can come back in a state of Nothingness, then you need to test for that and code the rest of your logic accordingly."?

    Did you even read the post, or are you just visiting to flame people and make yourself feel better?

    I have a problem with anonymous cowards who make these types of posts calling people "a fraud". Generally these are people who are disturbed in some way, feel inferior, or harbor hatred that is not grounded in facts or logic. Get some help.

    ReplyDelete
  5. Anonymous8:12 AM

    I can see that your a good programmer, but your Easy Collapsible HTML page sections only work in IE and not any standards complient web browser.

    ReplyDelete
  6. You probably missed the updated one:

    http://www.eggheadcafe.com/tutorials/aspnet/2c0ba302-d7a5-453d-9b63-6e9095a9597a/easy-crossbrowser-collap.aspx

    ReplyDelete
  7. Anonymous4:08 AM

    Your point about n00bs is correct, but I can't say I agree with carte blanche decoration of one's code with try...catch. If anything you were the one who originally made me realise what a bad idea this is:

    http://www.eggheadcafe.com/articles/20030127.asp

    Unless it's intentional that an object reference returns null, in which case the logic should control the flow, I would recommend instead using Debug.Assert(myObject!=null). Of course this is pointless for production code but then if the code is bad the application *should* crash.

    ReplyDelete
  8. I guess this is a case of "not getting the point across specifically enough" on my part. Really, I totally agree, but the main thrust of the post was "Learn how to use the try / catch pattern to debug your code", not "how to catch exceptions best practices". Thanks.

    ReplyDelete
  9. Anonymous8:39 AM

    I agree Peter, this is good advice. I started with exception handling just like this, very generic error handling. I think it is a good practice for n00bs and it will make them familiar with certain exceptions. They will surely gain experience on the cause of these exceptions, and note what needs to be remembered to avoid the exception in future similiar coding situations.

    The only thing I would disagree with is printing the entire stack trace. Isn't that fairly expensive?

    ReplyDelete
  10. if you are debugging code that is returning a null reference exception, printing the stacktrace to the debug window will show you the line of code where your exception occcured. This is debugging, not production code. If you use Debug.WriteLine, it will be ignored by the compiler in a release build anyway.

    ReplyDelete
  11. Peter, you are missing the key argument here.

    Your main mistake is to use try-catch to catch code error.

    That's wrong approach (no matter what type of exception you are going to catch).

    try-catch hides error from you, even if it's logged.

    The app has to blow up to the face of programmer in case of obvious code mistake.
    With try-catch construct debugging is consuming considerably more time. In fact you are making problem even worse than it was in the beginning ("Object Reference Not Set to an Instance of an Object").

    ReplyDelete
  12. Dennis,
    I repectfully disagree. The main point I make is that I am a newbie programmer and I don't have any try/ catch blocks in my code (mistake number 1). If my code blows up and I see that I have an object reference... exception, usually I will have great difficulty finding out not only which object, but where in my code it actually happened. Using a temporary try / catch / generic System.Exception block around my code helps you to zero in on bad code. For production, once you've discovered what you did wrong, then you can go ahead and use best-practices exception handling as you describe.

    ReplyDelete
  13. Anonymous9:46 PM

    You don't need a try / catch at all if you are using Visual Studio, it will break at the point the exception is raised (first chance exception) and pop up an error box. No need for try/catches.

    ReplyDelete
  14. Yes, that's true, but unfortunately, not all the time, especially with ASP.NET web applications.

    ReplyDelete
  15. Peter,

    if you put try-catch block around all potentially suspicious code -- you'll have to identify such places first.
    If you are able to identify such places --- what the point to use try-catch?

    If you simply put try-catch code around almost everything your code would be at least 2 times as big, which would raise complexity of the code by 4 times.
    That in itself would cause terrible pain in development.
    Especially for juniors.

    Think also about the situation, when try-catch code itself has some error in. That would be very likely consequence of implementing your advise.


    If you run you ASP.NET app in debug mode -- almost always VS.NET would pinpoint exact problem.
    The only two exceptions I know:
    1) VS.NET is not in a very good shape -- that can be fixed by VS.NET reload.
    2) Try-catch block - which obfuscates error. That's another very strong reason not to use try-catch for your scenario.

    ReplyDelete
  16. In the strictest sense, no you do not have to "identify such places". While developing and debugging an application, I frequently wrap an entire method body in a try / catch block. Later on, I tune it up for specific exceptions.

    A simple try / catch block that only outputs an exception message and stacktrace won't have errors itself, so that is a moot point.

    There are many instances when both in ASP.NET and in class library or Windows Forms applications that the debugger will not target specific lines of code when an exception is thrown, particularly in multi-expression statements.

    Here is an example - the static constructor of the Entities class throws a type initialization exception and there is NO WAY that I know of to find the exact line without using a try / catch wrapper while developing:

    http://www.eggheadcafe.com/tutorials/aspnet/ca7f59b0-e086-4974-9130-3210625e675c/html-entities-class.aspx

    ReplyDelete
  17. Peter,

    Yes, your example (link) really doesn't point to exact line in the class which blows up.

    But I use 2 ways to pinpoint problem line of code, and in both cases it took ~3 minutes.

    Way #1:
    Rolling breakpoint or step by step execution.
    I simply moved breakpoints further and further in code with ~10 lines increment until I found out where it blew up.
    Then I moved one line at a time, until I found the line.

    Way #2:
    In win forms app I simply let exception be thrown blow. Visual Studio then let me review the content of exception, and the number of line was under "View Detail" -> Inner Exception -> StackTrace.

    Under ASP.NET 2.0 project pinpointing this line was even easier. Browser simply showed me exact problem line immediately.
    I didn't even need to turn on debugging in Visual Studio.
    That basically meant no debugging time at all.

    Of course it works only if there is NO try-catch block around problem code.

    I guess it's a good time to you reconsider your debugging approach
    ;-)

    ReplyDelete
  18. Anonymous3:33 AM

    You said it dude!!!! :)
    Noobs are asking questions way to fast these days, I think because it's so easy nowadays with all the online communities

    If they just google for this error(which they forget often), and READ alot, most of the time they'll be able to figure it out for themselves.

    Nice blogpost's/articles peter ;)

    ReplyDelete
  19. Anonymous11:41 AM

    There is the unfortunate case when you are unable, in ALL cases you've tried, to reproduce the error consistently.

    Sure, there's a bug, and yes, it's caught in a try/catch, but for whatever reason it still (seemingly randomly) happens.

    IMHO (which isn't worth much), admittedly) your anger is mis-placed. It's not the lack of knowledge about how to debug your own code, it's the fact that SO many people post the same damn question and don't bother to search for it first.

    So do yourself a favor, take a deep breath, and come down off your high horse eh?

    ReplyDelete
  20. My answer would've been to Google it rather than waste forum time. When .NET was new it used to be hard to find answers but it isn't anymore.

    The real trouble though is that there are no dollars in capital budgets for proper training and certification and it's too expensive for individuals to afford. We're expected to do a job without the requisite training or experience so we learn on the job, under stress and deadlines.

    Or... programming is so cheep that its outsourced to India. Someday people won't even know how to use a calculator much less do math in the brain.

    ReplyDelete
  21. What if I get this error on the "Finally" statement itself, with an inner exception in System.Runtime.Reflection? What object is causing that?

    ReplyDelete

Post a Comment

Popular posts from this blog

Some observations on Script Callbacks, "AJAX", "ATLAS" "AHAB" and where it's all going.

IE7 - Vista: "Internet Explorer has stopped Working"

FIREFOX / IE Word-Wrap, Word-Break, TABLES FIX

System.Web.Caching.Cache, HttpRuntime.Cache, and IIS Recycles

FIX: Requested Registry Access is not allowed (Visual Studio 2008)