System.ListException: List index out of bounds: 5
What does this error mean?
Apex lists are zero-indexed — the valid index range for a list of n elements is 0 to n-1. Accessing any index outside this range throws System.ListException. In SOQL contexts, this often happens when code assumes a query will return a certain number of records but the actual result set is shorter.
Common Causes
1. Assuming a fixed number of query results
Code that does results[0], results[1], etc. without checking the list size first — if the query returns fewer records than expected, any index access beyond the last element throws.
2. Off-by-one errors in loops
Iterating for (Integer i = 0; i <= list.size(); i++) — note <= instead of < — accesses one index beyond the list boundary on the last iteration.
3. Empty query result passed to downstream code
A method that expects a populated list receives an empty one because the query filtered out all records, and then indexes into it.
How to Fix It
Solution 1: Always validate size before indexing
List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :accId];
// ❌ BAD — no size check
Contact primary = contacts[0]; // throws if empty
// ✅ GOOD — check before accessing
if (!contacts.isEmpty()) {{
Contact primary = contacts[0];
}}
// ✅ GOOD — safe with ternary
Contact primary = contacts.isEmpty() ? null : contacts[0];
Solution 2: Use correct loop boundary
// ❌ BAD — <= causes out-of-bounds on last iteration
for (Integer i = 0; i <= myList.size(); i++) {{ ... }}
// ✅ GOOD — < is the correct boundary
for (Integer i = 0; i < myList.size(); i++) {{ ... }}
// ✅ BETTER — use for-each when you don't need the index
for (Contact c : contacts) {{ ... }}