Print this page

System.ListException: List index out of bounds: 0

Knowledge Article Number 000181121

The error means that the query has returned no records that match the criteria.  

Consider the following Scenario,
- You have a List that is used to store the data by executing some query.
- The query returned no rows to the List after execution.
- You are also using those field(s) in your class or trigger.
- In this case you will get a System.ListException: List index out of bounds: 0


If you then attempt to access an element at row 0, this will throw an error as that row doesn't exist. It's good practice to check there are records first in order to make sure that the list is not empty before accessing it:

Consider the following Example:

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

Before referring to the 0th index of list you must perform a check on whether the list is empty or not. Whenever you try to access records from list first check if its empty or not.

promote demote