0

I have a list of string that is built dynamically (so size is not always the same). I am trying to access specific indexes in the list but only if it exists/has value.

for(Id ids : uniqueHeadersToClone.keySet()){
    for(APTPS_Quote_Output_Footer1__c foot : mapHeaderIdToFooterList.get(ids)){
        splitFooterArray = String.join(innerMapStringOfFooterValues.get(ids), '££').split('££');
        newFooterToClone = new Footer1__c(Header__c = uniqueHeadersToClone.get(ids).Id, Value1__c = String.isNotBlank(splitFooterArray.get(1)) ? splitFooterArray.get(1).trim() : null, Value2__c = String.isNotBlank(splitFooterArray.get(2)) ? splitFooterArray.get(2).trim() : null, Value3__c = String.isNotBlank(splitFooterArray.get(3)) ? splitFooterArray.get(3).trim() : null, Value4__c = String.isNotBlank(splitFooterArray.get(4)) ? splitFooterArray.get(4).trim() : null);
        newFooterToCloneList.add(newFooterToClone);
    }
}
insert newFooterToCloneList;

this throws up

list index out of bounds: 4

error because 4 is the last index. Is there a way to try catch the error but still able to save object, with indexes 0 to 3?

thanks

1 Answer 1

4

Try adding another condition splitFooterArray.size() > x as below. I hope it will work.

The line break is added for better readability. Please update the syntax if there is any issue.

for(Id ids : uniqueHeadersToClone.keySet()){
    for(APTPS_Quote_Output_Footer1__c foot : mapHeaderIdToFooterList.get(ids)){
        splitFooterArray = String.join(innerMapStringOfFooterValues.get(ids), '££').split('££');
        newFooterToClone = new Footer1__c(
        Header__c = uniqueHeadersToClone.get(ids).Id,
        Value1__c = (splitFooterArray.size() > 0 && String.isNotBlank(splitFooterArray.get(1))) ? splitFooterArray.get(1).trim()) : null,
        Value2__c = (splitFooterArray.size() > 1 && String.isNotBlank(splitFooterArray.get(2))) ? splitFooterArray.get(2).trim()) : null,
        Value3__c = (splitFooterArray.size() > 2 && String.isNotBlank(splitFooterArray.get(3))) ? splitFooterArray.get(3).trim()) : null,
        Value4__c = (splitFooterArray.size() > 3 && String.isNotBlank(splitFooterArray.get(4))) ? splitFooterArray.get(4).trim() : null);
        newFooterToCloneList.add(newFooterToClone);
    }
}
insert newFooterToCloneList;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .