Platform
Apex list index out of bounds: check the position
Fix empty-list and invalid-index access in Apex with explicit size checks, stable iteration and tests for changing collections.
A non-null list can still contain no elements. Accessing position zero then throws a list-index exception.
Apex lists are zero-indexed, so a list with size() elements has valid positions from zero through size() - 1. Both ends matter when the index comes from a request or a calculation.
Check the index you will use
This illustrative fragment assumes values is a list and requestedIndex is an Integer input. The check rejects null, negative and oversized positions before reading the element.
if (values != null && requestedIndex != null &&
requestedIndex >= 0 && requestedIndex < values.size()) {
Object selected = values[requestedIndex];
// Continue with the selected value's documented type.
} else {
// Return the operation's invalid-position result.
}
For the simpler “first result if present” case, isEmpty() is easier to read. But selecting the first record must still make sense for the business task. A list returned without a deliberate ordering shouldn’t be treated as a ranked recommendation.
The null-safe operator protects a null receiver; it doesn’t make an invalid numeric index valid. A null list, an empty list and a list containing a null element are distinct cases.
Inspect changes to the collection
A loop using i <= records.size() reaches one position too far. Prefer a for-each loop when the numeric position isn’t needed. When removing items while iterating, use an approach that deliberately accounts for the changing size and shifted positions.
Pagination is another common boundary. The final page may contain fewer items than the requested page size. Process the returned items rather than assuming every response contains the maximum.
Trigger context needs its own check. Consult the supported variables for the event instead of assuming old-record data exists on insert. Unavailable context variables can cause null-related failures, which aren’t the same as an empty list.
Test the smallest collections first
Test an empty list, one item, the last valid index and the first invalid index. Include negative and null indices when callers can provide them. If your code removes or filters elements, test the case where all elements are removed.
For bulk operations, assert that each eligible record is processed. A blanket catch around list access can turn a visible failure into silent omission.
If the list came from a query, distinguish this error from single-SObject assignment. The query may have completed successfully and returned an empty collection; the unsafe step is the later positional access.