Loading

How to Resolve NullPointer Exceptions in Salesforce Apex Classes

Fecha de publicación: Oct 16, 2025
Tarea

You want to fix a NullPointer Exception error in an Apex class.

Pasos
  1. Identify the Line Number: Look at the error message to find the specific line number where the NullPointer Exception occurred. This tells you exactly where the issue is in your Apex code.
  2. Examine the Code at the Line Number: Go to the Apex class in your Salesforce org. In Setup (the gear icon, then select Setup), use the Quick Find box to type 'Apex Classes' and select it. Click the name of the Apex class that has the error. 
  3. Check for Uninitialized Variables: At the identified line, see if any variables or objects are being used before they have been assigned a value. For example, if you declare `MyObject__c myObj;` but never assign `myObj = new MyObject__c();` or `myObj = [SELECT Id FROM MyObject__c LIMIT 1];` before trying to access `myObj.SomeField__c`, a NullPointerException will occur.
  4. Check for Null Query Results: If the error occurs after a SOQL query, the query might be returning no records. Apex will return 'null' if a single record query (e.g., `SELECT Id FROM Account WHERE Name = 'NonExistentAccount'`) finds no matches. Always check if the query result is null before trying to access its properties. For example, use `if (myQueryResult != null) { ... }`.
  5. Use Null Checks: Implement explicit null checks for all objects or variables that could potentially be null before you attempt to dereference them (i.e., access their methods or properties).
  6. Review Collections (Lists, Sets, Maps): If you are iterating through a collection, ensure the collection itself is not null before looping. For example, `if (myList != null && !myList.isEmpty()) { for (MyObject__c obj : myList) { ... } }`.
  7. Test Your Changes: After adding null checks and initializing variables, save your Apex class and run any relevant test classes to ensure your changes resolve the error and don't introduce new issues.
  8. Monitor Debug Logs: If the error persists or you need more insight, enable debug logs for the user encountering the error. In Setup, type 'Debug Logs' in Quick Find and select it. Click 'New' to create a new debug log for the user. Run the action that causes the error, then examine the log for more details about the null value. 
Número del artículo de conocimiento

005226724

 
Cargando
Salesforce Help | Article