Loading

Apex: How to Fix 'System.ListException: List index out of bounds' Error

Publiceringsdatum: Jun 3, 2026
Beskrivning

The System.ListException: List index out of bounds: 0 error occurs in Salesforce Apex when code attempts to access an element at a specific index in a List, but that index does not exist. The most common cause is a SOQL query that returns zero records — when the list is empty and the code tries to access lstAccount[0], Apex throws this error because there is no element at index 0. This article explains why this error occurs and how to prevent it.

Lösning

How to Check If a List Is Empty Before Accessing Elements

Before referencing the 0th index of a list, always check whether the list contains records. The following Apex example shows how to guard against this error using a size check. The code only processes lstAccount[0] if the list contains at least one record:

List lstAccount = [Select Id, Name from Account Limit 10];
// Before processing the list check if its empty or not
// It will go inside the loop only if the List is having values in it.
if(lstAccount.size() > 0) {
 // Do something with lstAccount[0].Name
 }
// If you try to access lstAccount[0] without empty check then it will obviously throw that error!!

Common Causes of List index out of bounds Error

  • The SOQL query returned no rows to the List after execution.
  • The code references fields on a List element at an index that does not exist (for example, index 0 when the list is empty).
  • The List is populated in one context but accessed in a trigger or class where the query conditions do not match any records.
Knowledge-artikelnummer

000385743

 
Laddar
Salesforce Help | Article