System.ListException: List index out of bounds Exception in Salesforce

System.ListException: List index out of bounds Exception in Salesforce

To avoid the System.ListException: List index out of bounds Exception in Salesforce, make sure the size of the list is checked before fetching list values using the index.

For example, if you are trying to fetch list variable’s second index values, make sure the size of the list is greater than or equal to 3. 

Note:

Index starts from 0 and not from 1.

Sample Code to reproduce the issue:
List < Account > listAccounts = [ SELECT Id, Name FROM Account WHERE Name = ‘Test’ ];
System.debug( ‘First Account Name is ‘ + listAccounts.get( 0 ).Name );

Fix for the above code:
List < Account > listAccounts = [ SELECT Id, Name FROM Account WHERE Name = ‘Test’ ];

if ( listAccounts.size() > 0 ) {
    
    System.debug( ‘First Account Name is ‘ + listAccounts.get( 0 ).Name );
    
}

Reference Help Article:

https://help.salesforce.com/s/articleView?id=000329067&type=1

Leave a Reply