[SalesForce] System.ListException: List index out of bounds: 1 in apex share

I am getting below error and not sure how to fix that ?

List<Case> csList = [Select Id,OwnerId, (select Id, OwnerId, CreatedById from Payment__r), 
                     (select Id,OwnerId,CreatedById from Payment_2__r) 
                     FROM Case 
                     WHERE Id IN ('XXXXX')];
System.debug('------------------------------------@@ : '+csList); 

for(Case c : csList){
    List<Payment__c> siList = csList[0].Payment__r;
    System.debug('======= '+siList);
    List<Payment_2__c> siList2 = csList[1].Payment_2__r;
    System.debug('======== '+siList2);
}

Getting below error:

System.ListException: List index out of bounds: 1

Best Answer

Don't index in unless you are sure there are adequate members in the collection. If it were empty, you would be getting the 0 index out of bounds instead. Make sure you check the size.

List<Payment__c> collection1, collection2;
if (csList.size() > 0) collection1 = csList[0];
if (csList.size() > 1) collection1 = csList[1];
Related Topic