System.NullPointerException: Attempt to de-reference a null object | Troubleshooting | Salesforce Error

Null Pointer Error 

Why I am facing System.NullPointerException error 

Offoo!! I tried writing the code and it's again hitting the error "System.NullPointerException: Attempt to de-reference a null object"w. I am really not sure what exactly is bothering my apex code 😭😩. I really tried very hard to complete the requirement but it's giving me this error now.

Relax Kid! It's just a code and it's designed to be fixed. Do you remember 'Every problem come up with its solution' Likewise this error is giving you the opportunity to not do mistakes again.

So let's roll on your sleeves because today we are going to learn about how to fix this error with the proper troubleshooting techniques and process which you can use in order to resolve this "System.NullPointerException" error (shhh... and for other errors too 🤫)  

Just Trust the process Kid...

Today we are going to understand :
1) When exactly we get this error (with scenario)
2) How you can troubleshoot it
3) How to fix it with proper understanding
4) Best practices to be followed to avoid this error

Let's get started...

Oops! I forgot to tell you, you may come across this error in multiple scenarios when writing the apex code in the salesforce but ultimately the methods which you will learn today are the secrets of your seniors.

Finally..Let's begin

What exactly does this weird error "System.NullPointerException: Attempt to de-reference a null object" means?

Now consider one real-life example: Let's suppose if I will give you A4 size blank white paper and ask you to read line number 4 paragraph of it ?? What will be your reaction 😒😏. You will say hey buddy there are no lines drawn on the page also, neither any paragraph is written over here. How can I even read those man!! 

Hence before reading those lines on a paragraph you should first have lines drawn and a paragraph written on that A4 size blank paper. Isn't it? Of course YES!!

Similarly, before you try to execute and compile your apex code there must be the value defined that you are trying to access. Same way, when your code will try to look for the value stored inside the variable and it turns out as 'Null'. This is why the system also throws an error and ask you to draw the lines first and then try to read those from paper (Apex code in our case). 
Hope the above example helps you to understand the background of the error.

In Formal definition, 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. 

Don't worry smartKid! we will break down those big words in more simpler version just be with me. 

When exactly we get this error in our code :

Let's consider a very basic trigger scenario to understand this error in more detail. As mentioned earlier, there can be multiple scenarios but our major focus in this episode is finding the root cause and the way we can fix it. It's similar for all.

Scenario: Write a trigger to update the value for the Phone number with '9999999999' whenever a new account is created.

Hmm... it seems so simple but I am writing the trigger for the first time but I will try to implement this.

Follow the steps :

STEP 1. Open your developer console.

STEP 2. Create a Trigger called as "AccountTrigger" on the Account object.

It will look like below code

====
trigger AccountTrigger on Account (before insert) {

}
====

Now, after writing the logic here as per the requirement.

Sample 1:
====
trigger AccountTrigger on Account (before insert) {
    List<Account> accList; 
    for(Account acc : accList)
    {
      acc.Phone = '9999999999';  
    }
}
==== 

Consider the above-weird sample code and Let's save this code...

STEP 3. Go to Accounts and try to create the new Account and hit Save
====
Salesforce Error
====


Oops!! its trowing "AccountTrigger: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.AccountTrigger: line 3, column 1

Mmm..okay 

How you can troubleshoot it :

STEP 4. Check your apex code

Now let's check the line number mentioned in our code i.e. line 3, column 1 

we have "for(Account acc: accList)" this code at line number 3.

Now just looking at the line number we will not be able to fix it right ? 

Next Step...

STEP 5 : Let's look at developer console logs 

As these logs will give you exactly where you are getting null values.
you will get the latest log in recent logs of log tab in your developer console like below:

====
Salesforce Error
====

Double click on these logs and check the executable checkbox in your developer console present on the bottom left side.

Here are the results :

====
Salesforce Error
====

Hey Kid!! Can you observe the highlighted line VARIABLE_ASSIGNMENT[2]|this.accList|null|0x1bd0e68c 

You understood it correctly, it is because when the trigger is executing the value it is trying to read for accList is null

Alternative : You also can put system.debug('Value of acclist is ::'+ accList) on before line number 3 to check what exactly the value is coming before using it.

Now time to fix it.

How to fix it with proper understanding :

STEP 6 : Check where it is defined.

We can observe that we only mentioned List<Account> accList; in our code and then directly using it right? it's not the correct way of instantiation of new account list. 

The proper instantiation for creating a new account List is :
List<Account> accList = new List<Account>();

Let's correct it...and check it out.

====
trigger AccountTrigger on Account (before insert) {
    List<Account> accList = new List<Account>();
    for(Account acc : accList)
    {
      acc.Phone = '9999999999';  
    }
}
====

Save it and now try to create a new account.

Now you will be able to create new Account without any error. Hurreyy!!

Wait...wait...wait...it's not over kid.

Check the phone field on your newly created account successfully and error is resolved. Oops!! it's blank that means the trigger is not working as expected.

Because now we have to correct our code, we need to use Trigger.new to iterate inside for loop instead of this list 

Corrected code after using trigger.new instead of accList :

====
trigger AccountTrigger on Account (before insert) {

    for(Account acc : Trigger.new)
    {
     acc.Phone = '9999999999';  
    }
}
====

Perfect...now if you try to run the above code it will create a new account record and update the Phone value with '9999999999' every time.

Result :
====
Salesforce Error

====

Hence the solution is to make sure the Object and/or the Attribute to be used is not null. 

Best practices to be followed to avoid this error :

We can add null checks every time when you are trying to access the new list or any value.

====
trigger AccountTrigger on Account (before insert) {

    for(Account acc : Trigger.new)
    {
    if(acc.Phone != Null){
     acc.Phone'9999999999'
    }
  }
}
====

Also, best way is to use Try/Catch blacks to add exception handling in your code.

for example (if we add it to our initial code):

====
trigger AccountTrigger on Account (before insert) {
    List<Account> accList;
try{
    for(Account acc : accList)
    {
     if(acc.Phone != Null){
     acc.Phone = '9999999999'
     
    }
   }
    catch(exception e){
    // Print the exception in debug logs instaed of showing on UI
    system.debug('This is exception ::'+ e);
    }
}
====

In the above code, after adding try/catch, your new account will save successfully every time you save the record but it will skip the code if there is an exception and you can check the exception in debug logs.

Just like this :
====
Salesforce Error
====


Hurreeyyy!!...Finally, we not only resolved the error with this weird trigger scenario but also we learned how you can troubleshoot the issue along with best practices and adding null checks inside your code.

These methods will always help you to troubleshoot and resolve this error quickly.

Please let me know which is the most annoying error you have faced or if you want me to write about any specific salesforce error in this troubleshooting series. 

Wish you all the very best!!..... Happy Learning ☁️⚡️

WOHOOO !! YOU HAVE JUST COMPLETED Troubleshooting for System.NullPointerException error EPISODE
If you like this SFDCkid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all ⚡️Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 

SFDCKid Footer


System.NullPointerException: Attempt to de-reference a null object | Troubleshooting | Salesforce Error System.NullPointerException: Attempt to de-reference a null object | Troubleshooting | Salesforce Error Reviewed by on Rating: 5

1 comment:

  1. hi ,this is very helpful. please add more error scenarios and their troubleshooting steps

    ReplyDelete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.