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

Reason:

This error is caused by a line of code that is trying to use an object that has not been instantiated, or an object's attribute that has not been initialized.


Example:

List<Account> accountList;

Account acc = new Account(); 

acc.Name = 'test'; 

accountList.add(acc);


Solution:

Make sure the Object or the Attribute to be used is not null.

Account newAccount = accountMap.get(oldAccount.Name);

if (newAccount != null) 

if (newAccount.Site != null) 

i = newAccount.Site.length();

Note, if the field Site was left empty, it will generate the error message as well.

Exception handling:

Account newAccount = accountMap.get(oldAccount.Name);

try {

i = newAccount.Site.length();

}

catch (System.NullPointerException e) {

e1 = e; // can be assigned to a variable to display a user-friendly error message

}


More Examples:


1.

Initialize the list or object.


Public List<Account> acc {get;set;}

acc = new List<Account>(); 


Whenever you use this list variable here - acc. Try to check size before you do an update or iteration.


Example:

if(!accList.isEmpty()) {

//Your code logic for accList.

}


Account acc;

acc.Name = 'sampleAccount';


above done properly:

Account acc = new Account();

acc.Name = 'sampleAccount';


3.

When you use list (or set) then also you need to allocate list (or set) like :

in List:

List<Account> accList = new List<Account>();

in Set:

Set<String> strSet= new Set<String>();


4.

If Map returns null and we try to use it in our code like here accountMap with Id as key and Account as value:


Account accRecord = accountIdAccountMap.get(accId);

System.debug('!!!!testing!!!!'+accRecord.Name);


Here in the above, accountIdAccountMap or accRecord can be null also. So, do null check.


if(accountIdAccountMap != null){

    Account accRecord = accountIdAccountMap.get(accId);

    if(accRecord != null){

        System.debug('!!!!testing!!!!'+accRecord.Name);

    }

}


5. 

Use isEmpty() method like:

if(!accList.isEmpty()){

     //Do your dml or other operations here

}


6.

Do Exception Handling:

try{

    //Code here

}catch(Exception e){

    //Handle exception here

}


Always set up log, to more details or the depth or root cause of the issue.



Reference:

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_exception_methods.htm

https://help.salesforce.com/s/articleView?id=000327918&type=1

Comments