The Java NullPointerException
I’ve decided to take this blog in a different direction and discuss one of the most annoying Java exceptions the NullPointerException. This is what happens when you try to use a object’s method when the object that it refers to is null. If I were to declare Shape object in the following manner Shape ashape = null;
and than attempt to use a method like this ashape.size(); a NullPointerException would than occur. The simplest way to avoid 90% of these exceptions it to simply check an object to see if contains a reference to a null object and than do something based on that.
if(ashape==null) {
// do this
}
else {
// do this
}
Sometimes this bugs are just a bit more problamatic to track down in the code but simply checking for a null reference before an object is used is usually the best option.
Tuesday, April 1st, 2008