Sidebar

What is a null pointer?

0 votes
291 views
asked Jul 3, 2013 by mike-r-7535 (13,830 points)

What is a null pointer exception and how do you prevent it?

1 Answer

+1 vote
 
Best answer

A null pointer is a declared variable that is not assigned to any value, or explicitly assigned as null.

Consider the following:

var streetAddress;

The variable has been declared, but it does not reference any value.  Like an envelope without an address, the streetAddress variable holds no value.  By attempting to access a property or call a function on the null value will cause a null pointer exception.

var streetAddress;
var streetAddressParts;
try {

   streetAddressParts = streetAddress.split(" ");
} catch (err) {
   qie.info("Told ya, we caught an error: " + err);
}
streetAddress = "459 Dirello Street";
streetAddressParts = streetAddress.split(" "); // no null pointer exception because it has a value

Always check if the variable is null before using any property or function on it.  This is a good habit when pulling from the messageCache just in case the cache was not defined (which would then return null).

var streetAddress = messasgeCache.getValue("address1");
var streetAddressParts;
if (streetAddress !== null) {
   streetAddressParts = streetAddress.split(" ");
}

Better safe than sorry.

answered Jul 3, 2013 by mike-r-7535 (13,830 points)
selected Jul 5, 2013 by sam-s-1510
...