[SalesForce] How to avoid List index out of bounds: 0

I have 2 queries in my code and result of 1st is used in 2nd query as below:

External_System_Mapping__c[] LeadProgram = [
    SELECT Salesforce_Value__c 
    FROM External_System_Mapping__c
    WHERE Mapping_Type__c = 'Program' 
    AND External_System_Value__c =:application_program
];

List<Lead> matchingLeadsListWIProgram = [
    Select Id, Status from Lead
    where isConverted = false
    and ((Program__c =: LeadProgram[0].Salesforce_Value__c)
    and (
        (Email != null AND Email = :application_email)
        OR (MobilePhone != null AND MobilePhone = :application_mobile)
        OR (Email != null AND Email=:spjat_email)
        OR (MobilePhone != null AND MobilePhone =:spjat_mobile)
    ))
];

But sometimes 1st query is returning null and I get this error:

List index out of bounds: 0

Any suggestions to avoid this error?

Best Answer

It is failing when you try to access the Salesforce_Value__c from the first record in your list of External System Mapping (LeadProgram[0].Salesforce_Value__c). You can check the size of the list before using it in the second query:

External_System_Mapping__c[] LeadProgram = [Select Salesforce_Value__c from External_System_Mapping__c Where Mapping_Type__c = 'Program' and External_System_Value__c =:application_program ];

if(LeadProgram.size() > 0) {
    List<Lead> matchingLeadsListWIProgram = [Select Id, Status from Lead where isConverted = false and ((Program__c =: LeadProgram[0].Salesforce_Value__c) and ( (Email != null AND Email = :application_email) OR (MobilePhone != null AND MobilePhone = :application_mobile) OR (Email != null AND Email=:spjat_email) OR (MobilePhone != null AND MobilePhone =:spjat_mobile))) ];
}
Related Topic