System.ListException

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

An exception is thrown when a list is used in a statement where the code is trying to access a value where there isn’t one.

In this article, we give you a quick help on how to avoid ‘System.Listexception: List Index out of Bounds‘ error.

Exception Cause

The main reason why we get the above error is when the list being referenced in code does not contain any values. For example: If you create a new list variable and then use it in a statement right away whether it has any values or not, then the list exception is thrown by the system.

List<Account> lstAccount = new List<Account>();

//Query Accounts
lstAccount = [Select Id, Name, Industry From Account Limit 10];

//Perform some logic that checks a value on a specific index
if(lstAccount[0].Industry == 'Media'){
   // The exception will be thrown because there were no results returned 
} 

Exception Solution

There are multiple ways a developer can deal with this error.

1. Check if list is empty before referencing it elsewhere

Always check if list is empty or not before referring to the 0th index of list.

List<Account> lstAccount = new List<Account>();

//Query Accounts
lstAccount = [Select Id, Name, Industry From Account Limit 10];

If(lstAccount.size() > 0){
   //Perform some logic that checks a value on a specific index
       if(lstAccount[0].Industry == 'Media'){
     // The exception will not be thrown as the logic will not run 
       } 
}

2. Wrap the logic in a TRY CATCH block to ensure exception is caught gracefully

Always wrap all logic in a TRY CATCH statement to ensure exceptions are caught and errors thrown gracefully and all actions are rolled back.

List<Account> lstAccount = new List<Account>();

try {
     //Query Accounts
     lstAccount = [Select Id, Name, Industry From Account Limit 10];
     //Perform some logic that checks a value on a specific index
     if(lstAccount[0].Industry == 'Media'){
            // The exception will be thrown but caught with the statement below
      }
 } catch (Exception e) {
   // Some debug statement
}

Conclusion

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