RP. ← Back to Blog
Bug Squash Series January 17, 2026

Collection Chaos: Handling Apex Crashes

Lists, Sets, and Maps are the heart of Apex. But one wrong index or a missing key can bring your entire transaction to a halt.

01. List Index Out of Bounds

The Crash ❌

List<Account> accs = [SELECT Id FROM Account LIMIT 0];
// Trying to access index 0 of an empty list
Id firstAcc = accs[0].Id;

The Pro Fix ✅

if(!accs.isEmpty()) {
  Id firstAcc = accs[0].Id;
} else {
  // Handle the empty state
}

02. Map Key Null Pointer

The Crash ❌

Map<Id, Contact> conMap = new Map<Id, Contact>();
// someId does not exist in the map
String name = conMap.get(someId).Name;

The Pro Fix ✅

// Use the Safe Navigation Operator
String name = conMap.get(someId)?.Name;

// OR Check if it contains the key
if(conMap.containsKey(someId)) { ... }

03. Concurrent Modification

The Crash ❌

for(Account a : accList) {
  // Cannot remove items from the list we are currently looping!
  accList.remove(a);
}

Pro Solution: Never remove items from a list while iterating over it. Instead, create a new list of "Items to Remove" and process them after the loop is finished.

01

Lists are ordered. The most common error is the ListIndexOutOfBoundsException, which happens when you ask for a seat that doesn't exist.

accList[index] // Index > Size = Crash
02

Sets ensure uniqueness. They are unordered, meaning you can't use an index. The "trap" here is forgetting that Sets are Case-Sensitive for strings.

mySet.add('RAM');
mySet.contains('ram'); // returns false
03

Maps are for bulkification. The danger zone is the NullPointerException when calling get() on a key that doesn't exist.

myMap.get(missingId).Name; // CRASH

The Collection Safety Checklist