6/29/2007

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!