Thursday, February 5, 2015

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


Below are few of the error which are encountered while working with soql and assigning values to variables.

There are situations when we need to check for null conditions. when we query  a sobject we must check the if the returened results are not null. Checking the null condition resolved many of the encountered errors. Lets see these with Examples
caused by: System.NullPointerException: Attempt to de-reference a null object

This Error is caused when there is no results in the query and the result is used which out checking the null condition.





Corrected Code-We need to add a check for null values to avoid this situation






System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.Name

This Error is caused by using the field which is not queried in soql query.


Corrected Code-We need to include all fields in soql query which is being in code.





System.QueryException: List has no rows for assignment to SObject

This error is caused when the query cannot get the result back.



Corrected Code-we need to check the where clause to see if the variable is not null























2 comments:

  1. Nice post...
    Are there any other scenario's we will be getting the same errors.

    ReplyDelete
  2. If i have a soql that is using lookup relationship and master details both combined, is using 5 level deep field info, the soql query does produce the correct info , however when I try to use it in code it is giving error

    System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.Name

    I put system.debug( junction_email__r.xyz_email__r.master_acc__r.membership__r.name); threw above error, however upto

    junction_email__r.xyz_email__r.master_acc__r.membership__c point it works.

    So is it a big? Soql does produce result but when you try to consume the same field which is 5 level deep it doesn't work

    ReplyDelete