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

The error “System.NullPointerException: Attempt to de-reference a null object” normally occurs when you try to reference an object which has not been initialized or has null values. It can also happen when your variable is not initialized. If we dont instantiate the object that contains the field before we reference it results in an 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:

 

We should use it like this:

 

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

 

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:

The code above also results in an error. In the above code accountIdAccountMap or accRecord can sometimes be null and result in this error aswell. knowing this we should always do null checks on most code no matter what it does. To make the above code safer to run see below:

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

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

 

 

Add Comment