System.NullPointerException: meaning and how to fix it

Apex runtime Checked against the official docs on Source: SOAP API Developer Guide: Core Data Types, StatusCode

Quick answer

System.NullPointerException: Code called a method or read a field on a variable that is null, such as an unqueried relationship, an empty map lookup or an uninitialised variable. Start with: Use the line and column in the stack trace to find the expression that is null.

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

Cause

Code called a method or read a field on a variable that is null, such as an unqueried relationship, an empty map lookup or an uninitialised variable.

How to fix System.NullPointerException

  1. Use the line and column in the stack trace to find the expression that is null.
  2. Add null checks, or use the safe navigation operator ?. in Apex.
  3. Initialise collections, and check map.get(key) results before using them.
String name = acc?.Owner?.Name; // returns null instead of throwing

Have a different message? Paste it into the error decoder, which matches it against 45 common Salesforce errors in your browser.

Frequently asked questions

What does System.NullPointerException mean in Salesforce?

Code called a method or read a field on a variable that is null, such as an unqueried relationship, an empty map lookup or an uninitialised variable.

How do I fix System.NullPointerException?

1. Use the line and column in the stack trace to find the expression that is null. 2. Add null checks, or use the safe navigation operator ?. in Apex. 3. Initialise collections, and check map.get(key) results before using them.

More Apex runtime errors

SFDX Talk is unofficial documentation. It is not affiliated with, endorsed by, or sponsored by Salesforce, Inc. Message text varies slightly by release and context, so confirm against the official page before relying on it.