All articles

Platform

Attempt to de-reference a null object in Apex

Find the null value in an Apex expression and choose an explicit outcome for missing input, absent map entries and optional relationships.

A null-pointer exception names the line, but that line may contain several dereferences. Split the expression before adding a catch block.

For accountsById.get(accountId).Owner.Name, the missing value could be the map, its lookup result or the relationship object. Identify the first missing value and trace who supplied it. A defensive change should preserve the business meaning of the operation.

Choose the missing-data behavior

An optional display field can remain empty. A required destination account should produce a validation response. A missing configuration record may require an operational alert. Returning null for all three cases makes the exception disappear while leaving the caller unable to distinguish them.

The null-safe operator returns null when its left operand is null. This small example uses it for optional display data:

Map<Id, Account> accountsById = new Map<Id, Account>();
Account selected = accountsById.get(accountId);
String displayName = selected?.Name;

Here accountId is an existing input variable. The empty map makes the lookup miss; displayName becomes null. Production code must decide whether that absence is allowed before using the value in a write or response.

The null-safe operator doesn’t validate array bounds, retrieve unselected fields or enforce a business requirement. Protect each nullable boundary in a chain; don’t add operators everywhere without understanding where the value originated.

Inspect the producer as well as the consumer

A map lookup may miss because the selector filtered out a record, the user couldn’t access it or the ID belongs to another org. Check those paths before creating a placeholder object that pretends the record exists.

Initialize collections you own, and document whether methods return an empty collection or null. Consistent return contracts reduce repeated defensive branches. For trigger context variables, verify that the event makes the variable available before reading it.

If a query did not select a field, adding a null check isn’t the fix. That is a different SObject access error and requires correcting the query or method contract.

Add the missing test case

Test absent input, a lookup that returns no record, an optional relationship and a valid record. Assert the intended error or result for each case, rather than merely asserting that the code doesn’t throw.

An agent action should return a bounded, understandable failure when required data is missing. It should not report that an update succeeded after skipping the operation. The useful fix makes the missing-data decision explicit at the point where the application can explain it.

Keep reading

All articles