home Homebuild Toolsbug_report Errorsmenu_book Guideslightbulb Tipssmart_toy Promptsextension Extensionsfolder_open Resourcesinfo About
search
error

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

What does this error mean?

This exception is thrown when Apex code calls a method or accesses a property on a variable whose value is null. In the context of SOQL, this most commonly happens when traversing a relationship field (contact.Account.Name) where the parent record lookup field is blank — making the parent object reference null.

Common Causes

1. Traversing a lookup relationship with a blank lookup field

A Contact whose AccountId field is null has a null Account relationship object. Accessing contact.Account.Name dereferences null.

2. Query returns 0 rows assigned to a variable

Using Database.query() or a list query where the result is empty, then indexing into it (results[0]) without checking size.

3. AggregateResult field accessed with wrong key

Calling ar.get('fieldName') with a misspelled alias or field name returns null, which when cast to a non-nullable type causes further null dereference.

How to Fix It

Solution 1: Use the safe navigation operator (?.) for relationship traversal

Apex
// ❌ BAD — throws if Account is null
String accName = contact.Account.Name;

// ✅ GOOD — safe navigation operator (Spring '22+)
String accName = contact.Account?.Name; // returns null if Account is null

// ✅ GOOD — explicit null check
String accName = (contact.Account != null) ? contact.Account.Name : '';

Solution 2: Check list size before accessing by index

Apex
List<Account> results = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];

// ❌ BAD — throws if list is empty
Account acc = results[0];

// ✅ GOOD — guard with isEmpty()
Account acc = results.isEmpty() ? null : results[0];
if (acc != null) {{
    System.debug(acc.Name);
}}
lightbulb

Pro Tip: The safe navigation operator ?. chains gracefully: opp?.Account?.Owner?.Name returns null at the first null link in the chain rather than throwing. Use it liberally for multi-level relationship traversals.