Attempt to De-reference a Null Object Error
What does it mean
This error indicates that your code attempted to access a method, a property of a variable, or an element of a collection where the variable itself holds a null value.
It means the system was expecting a valid object instance or a populated variable but found that it was undefined or pointing to nothing.
Solution
Identify the line number mentioned in the debug logs or the error message stack trace as the origin of the error.
Examine the variable just before the dot (.
) operator or the operation that caused the error.
Implement explicit null checks using an if (myVariable != null)
statement before attempting to access any of its members or perform operations on it.
Ensure that variables are properly initialized and assigned a non-null value before they are used in the code.
If the variable is populated by a SOQL query, add checks to verify that the query returned at least one record before processing the results.
If the variable is the result of a method call, ensure the method guarantees a non-null return or handle the case where it might return null.
Why it happened
The error occurs because the code tried to perform an action on a variable that held a null reference in memory.
Apex throws a System.NullPointerException
when it encounters an attempt to access or manipulate a variable that has not been instantiated or assigned an object reference.
Common scenarios include SOQL queries that return no records when assigned to a single sObject variable, accessing fields on a lookup relationship that is not populated, or trying to iterate over an empty or null list or map without checking.