function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
daniela tobardaniela tobar 

Error message: List index out of bounds: 0

Hi, good morning, I get the following error in the logs "Error message: List index out of bounds: 0" on line 52 of the code. 
This is the code of line 52, how can I validate or how can I fix the error?
 
new CampaignMembersService_SV().constructRegistrantCampaignMember(regData.optIn, newCon,ProfHubEmailSendSelector_SV.newInstance().selectByMasterLabel(new Set<String> {countryMap.get(regData.country)})[0].Communication_Optin__c, uow);

Thanks!
Best Answer chosen by daniela tobar
Prateek Prasoon 25Prateek Prasoon 25
The error message "List index out of bounds: 0" typically occurs when you try to access an element in a list using an index that is out of range. In this case, it seems like the error is happening on line 52 of your code.
To fix this error, you need to ensure that the list you're trying to access has at least one element before accessing it. Here's an updated version of your code that includes a check to validate the list before accessing its first element:
List<String> communicationOptinList = ProfHubEmailSendSelector_SV.newInstance().selectByMasterLabel(new Set<String>{countryMap.get(regData.country)});
if (communicationOptinList.size() > 0) {
  new CampaignMembersService_SV().constructRegistrantCampaignMember(regData.optIn, newCon, communicationOptinList[0].Communication_Optin__c, uow);
} else {
  // Handle the case when the list is empty, possibly by providing a default value or throwing an exception.
}

If you find this answer helpful,Please mark it as the best answer.