Loading

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

게시 일자: Jul 17, 2024
상세 설명

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.

솔루션

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 기사 번호

000385743

 
로드 중
Salesforce Help | Article