Loading
Ongoing maintenance for Salesforce HelpRead More
Feature degradation | Gmail Email delivery failureRead More

'System.ListException: List index out of bounds' error

Publish Date: Jul 17, 2024
Description

This article explains why a 'System.ListException: List index out of bounds: 0' error occurs when trying to access a list, and how to resolve it.

Resolution

If we attempt to access an element at row 0, the code will throw an error if no data exists at row 0.  It is a  good practice to check whether there are records in the list before accessing any element from that list.

Check if list is empty

Before referring to the 0th index of a list, here is sample code to check on whether the list is empty or not.

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!!

Considerations for an empty list

  • The query returned no rows to the List after execution.
  • If those field(s) are referenced in a class or trigger.
  • In this case we will get a System.ListException: List index out of bounds: 0
Knowledge Article Number

000385743

 
Loading
Salesforce Help | Article