If you’ve written more than a few lines of Apex, you’ve almost certainly run into one of the most common and challenging errors on the Salesforce platform:

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

This error is the Apex equivalent of asking for address from a person who isn’t there.

This guide from Salesforcehour will break down exactly what this error means, the common scenarios that cause it, and the best practices you can use to resolve and prevent it .

What is a System.NullPointerException?

At its core, a NullPointerException is very simple. It means you have a variable in your code that you expect to hold a value, but it doesn’t. It’s null. When your code tries to use that null variable for example, to access one of its properties or call one of its methods the system has no object to work with and throws the error.

Think of it like trying to read page 50 of a book, but you were never handed the book in the first place.
In the same way Your variable is the empty hand, and trying to “read” from it is the action that causes the error.

What Causes the “Attempt to de-reference a null object” Error?

This error can appear in many situations, but it almost always comes down to one of these common scenarios.

Scenario 1: A SOQL Query for a Single Record Returns No Results

This is the most frequent cause. When we write a SOQL query that is expected to return a single sObject record and it finds nothing, the variable it’s assigned to becomes null.

Example:

// This query might not find any Account with this name
Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Salesforcehours' LIMIT 1];

// If no account is found, 'acc' is null.

// The next line will throw the NullPointerException because you can't get the Id of nothing.
System.debug('The Account ID is: ' + acc.Id);


Scenario 2: Accessing a Field from a Related Object That Wasn’t Queried

You can access fields from parent records directly in Apex (e.g., myContact.Account.Name), but only if you explicitly included them in your SOQL query. If you forget to query the parent fields, the parent object itself will be null.

Example:

// We forgot to query the parent Account's Name field
Contact con = [SELECT Id, LastName FROM Contact WHERE Name = 'Tim Tapers' LIMIT 1];

// The next line will throw the NullPointerException.
System.debug('The Account Name is: ' + con.Account.Name);


// 'con.Account' is null because it was not queried.


Scenario 3: Working with an Uninitialized Collection (List or Map)

When you declare a collection variable like a List or Map, you are only creating a placeholder for it. You must also initialize it using the new keyword before you can add items to it.

Example:

List<Account> accountList; // The list is declared, but it is null.

// The next line will throw the NullPointerException because you can't add an item to a list that doesn't exist yet.
accountList.add(new Account(Name='My New Account'));


Scenario 4: Accessing a Map with a Key That Doesn’t Exist

When you use the .get() method on a Map, it returns the value for that key. If the key does not exist in the map, it returns null. Trying to use that null result will cause the error.

Example:

Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Name FROM Account LIMIT 10]);
Id nonExistentId = '001xx0000000000XXX'; // An ID that is not in the map

Account acc = accountMap.get(nonExistentId); // 'acc' is now null

// The next line will throw the NullPointerException.
System.debug('The Account Name is: ' + acc.Name);


Scenario 5: Accessing an Element from an Empty List

While a query that returns no records will result in an empty list (not a null list), trying to access an element from that empty list will still cause an error.
The error is different (System.ListException: List index out of bounds), but it stems from the same root problem of assuming data exists when it doesn’t. Many developers mistake this for a NullPointerException.

Example:

List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name = 'A Non-Existent Company Inc.'];

// 'accountList' is not null, but it is empty (size is 0).
// The next line will throw a ListException because there is no element at index 0.
Account acc = accountList[0];

How to Resolve and Prevent NullPointerExceptions

The key to fixing and avoiding this error is to practice defensive coding. This means always assuming a variable could be null and checking for it before you use it.

Best Practice 1: Always Perform Null Checks

This is the most effective solution. Before you use an object, especially one returned from a query or a map, check if it’s null.

// Query for a single record that might not exist
Account acc = [SELECT Id FROM Account WHERE Name = 'A Non-Existent Company Inc.' LIMIT 1];

// The Fix: Check for null before using the variable.
if (acc != null) {
    System.debug('The Account ID is: ' + acc.Id);
} else {
    System.debug('No account was found with that name.');
}


Best Practice 2: Initialize Your Collections

Always initialize your Lists, Sets, and Maps before you use them. This is a simple but critical step.

// The Fix: Initialize the list with the 'new' keyword.
List<Account> accountList = new List<Account>();

// Now you can safely add items.
accountList.add(new Account(Name='My New Account'));


Best Practice 3: Query into a List for Safety

A SOQL query for a single record can return null. A SOQL query for a List of records will mostly not return null .If no records are found, it will return an empty list. You can then safely check the list’s size before trying to access its elements.

// Safer: Query into a List. 'accountList' will be empty, not null.
List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name = 'A Non-Existent Company Inc.'];

// The Fix: Check if the list is empty before accessing an element.
if (!accountList.isEmpty()) {
    Account acc = accountList[0];
    System.debug('The Account ID is: ' + acc.Id);
}


Best Practice 4: Use the Safe Navigation Operator (?.)

For traversing relationships between objects, the Safe Navigation Operator is a modern and concise way to prevent NullPointerException. It stops evaluating an expression if it encounters a null value and simply returns null instead of throwing an error.

Old Way (with nested checks):

String accountName;
Contact myContact; // This could be null
if (myContact != null && myContact.Account != null) {
    accountName = myContact.Account.Name;
}


Modern Way (with Safe Navigation Operator):

Contact myContact; // This could be null
// This is much cleaner. If myContact or myContact.Account is null, accountName will just be null.
String accountName = myContact?.Account?.Name;


This is especially useful in LWC controllers or complex triggers where you need to access data several levels deep.

A Simple Demo: From Bug to Fix

Here is a simple example you can run yourself in the Developer Console to see the error and the fix in action.

The Buggy/Bad Code

This code tries to update the industry of an Account that doesn’t exist.

// Open the Developer Console (Anonymous Window) and run this code.
// It will fail because the query returns null.

Account myAccount = [SELECT Id, Industry FROM Account WHERE Name = 'This Company Does Not Exist'];

// This line causes the error because myAccount is null
myAccount.Industry = 'Technology';

update myAccount;

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

System.NullPointerException


The Fixed Code

This version uses the safer “query into a list” pattern to prevent the error.

// Now, run this fixed version in the Developer Console.
// It will run without errors and print a debug message.

List<Account> myAccounts = [SELECT Id, Industry FROM Account WHERE Name = 'This Company Does Not Exist'];

// The Fix: Check if the list is empty before proceeding.
if (!myAccounts.isEmpty()) {
    Account myAccount = myAccounts[0];
    myAccount.Industry = 'Technology';
    update myAccount;
    System.debug('Account updated successfully!');
} else {
    System.debug('No account found to update.');
}

How to Fix System.NullPointerException in Salesforce Apex

How to Fix System.NullPointerException in Salesforce Apex

BOOM !!! You do not need to worry about NullPointerException anymore

Salesforce Help Article: For official guidance, you can refer to this Salesforce Help Article

Summary

The “Attempt to de-reference a null object” error is a fundamental challenge in Apex development, but it is almost always preventable. By adopting defensive coding habits such as always checking for null values, initializing collections, using the Safe Navigation Operator, and querying into lists instead of single objects . We can write more robust and error-free code.

Author

  • Salesforce Hours

    Salesforcehour is a platform built on a simple idea: "The best way to grow is to learn together". We request seasoned professionals from across the globe to share their hard-won expertise, giving you the in-depth tutorials and practical insights needed to accelerate your journey. Our mission is to empower you to solve complex challenges and become an invaluable member of the Ohana.


Discover more from Salesforce Hours

Subscribe to get the latest posts sent to your email.

Leave a Reply

Discover more from Salesforce Hours

Subscribe now to keep reading and get access to the full archive.

Continue reading