Based on the concept we cleared in the previous blog (please read Part 1 and Part 2 of this blog to get a more clear idea). There are two scenarios possible where Attempt to dereference error can take place.

– When your object is not initialized (already discussed in the previous blog)

– When your object has null values

Cause 2: Further, when you are accessing certain collections or an object on a visual force page, and your object value turns out to be null, your reference table can’t return your values from a null object. Hence this error can occur again.

For Example:

map<String, Account>AcctMap = new map<String,Account>();

String key = ‘hey’;

system.debug(AcctMap.get(key));     // it will return null as it has no value – soft stop

system.debug(AcctMap.get(key).name);     // it will return Attempt to dereference null object error – hard stop

Again, you can access value from a null object. Same null.name scenario which doesn’t work out.

In this case, the solution is easy.

–    Put in some value in the map then try to access the needed.

For Example:

map<String, Account>AcctMap = new map<String,Account>();

Account acct = new Account (name=’HeyAccount’, custom_field__c=’Thanks for reading my blog!!’);

AcctMap.put(key,acct);         // pouring value

system.debug(AcctMap.get(key));     // it will return value

system.debug(AcctMap.get(key).name);        // it will return null – soft

OR

–    You can apply null pointer checks that will fulfill your work. This may eradicate the error but may affect further processing. We suggest finding out the root cause why there is no data in the field and work accordingly.

For Example:

map<String, Account>AcctMap = new map<String,Account>();

String key = ‘hey’;

If(AcctMap!=null)     // next will only be executed if this check is true

system.debug(AcctMap.get(key));     // it will return null as it has no value – soft stop

if(AcctMap!=null &&AcctMap.get(key)!=null)     // next will only be executed if this check is true

system.debug(AcctMap.get(key).name);     // it will return Attempt to dereference null object error – hard stop

This works same for all collections and objects.

Keep Reading !