System.NullPointerException: Attempt to de-reference a null object

System.NullPointerException: Attempt to de-reference a null object

How to solve System.NullPointerException: Attempt to de-reference a null object error

System.NullPointerException: Attempt to de-reference a null object is very common error in apex class.  It occurs when your variable (sobject, list, set or any other data type) is not initialized (allocated memory). In order to use the non primitive data type in the code we need to initialize the memory first. If we don’t do that it may result in Attempt to de-reference a null object error. This error may occur in Apex classes, Visualforce pages with Apex controller, Test classes, Apex Triggers.

For Example if I use like this:

Account acc;
acc.Name = 'sfdcpoint';

It will result in attempt to de-reference a null object error.

We should use it like this:

Account acc = new Account();
acc.Name = 'sfdcpoint';

When we use list or set then also we need to allocate memory to list or set like this

List<Account> accList = new List<Account>();
Set<String> strSet= new Set<String>();

Same way this error can occur when we get null result from map and we try to use it in our code. For example we have accountMap with Id as key and Account as value:

Account accRecord = accountIdAccountMap.get(accId);
System.debug('*****accRecord.Name'+accRecord.Name);

Above code will also result in error. Here in above code accountIdAccountMap or  accRecord can be null. So we should do null check before using it like this.

if(accountIdAccountMap != null){
    Account accRecord = accountIdAccountMap.get(accId);
    if(accRecord != null){
        System.debug('*****accRecord.Name'+accRecord.Name);
    }
}

It is also very good practice to use isEmpty() method like this:

if(!accList.isEmpty()){
     //Do your dml or other operations here
}

As a best practice we should always do exception handling in our code like this

try{
    //Code here
}catch(Exception e){
    //Handle exception here
}

If you get System.NullPointerException. Its advisable to use System.debug to debug line of code which is resulting in this error and then fix it.

Happy coding 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/system-nullpointerexception-attempt-to-de-reference-a-null-object/