0

Getting "System.ListException: List index out of bounds: 0" even though I am checking if the list is empty or not. Any ideas?

trigger ABTestingAutonumber on Account(before insert, before update) {
    list < Account > a = [SELECT Id, AB_Testing_Autonumber__c FROM Account WHERE AB_Testing_Autonumber__c != null ORDER BY AB_Testing_Autonumber__c DESC LIMIT 1];
    Decimal maxlead = a[0].AB_Testing_Autonumber__c;
    if (a.size()>0) {
        for (Account a2: Trigger.new) {
            if (a2.OwnerId == '00537000000Qsqj') {
                a2.AB_Testing_Autonumber__c = Integer.valueOf(maxlead) + 1;
            } else {
                a2.AB_Testing_Autonumber__c = 1;                                    
            }
        }
    }
}
  • 2
    Decimal maxlead = a[0].AB_Testing_Autonumber__c; will fail if no records are returned – cropredy Aug 14 '15 at 18:43
  • You are checking the size of a after making a[0] and it will fail if no records returned. – Vigneshwaran G Aug 14 '15 at 18:46
1

This would be inside if(a.size()>0). For a empty list a[0] will throw exception.

Decimal maxlead = a[0].AB_Testing_Autonumber__c;

Change the logic to:

trigger ABTestingAutonumber on Account(before insert, before update) {
    list < Account > a = [SELECT Id, AB_Testing_Autonumber__c FROM Account WHERE AB_Testing_Autonumber__c != null ORDER BY AB_Testing_Autonumber__c DESC LIMIT 1];
    if (a.size()>0) {
        Decimal maxlead = a[0].AB_Testing_Autonumber__c;
        for (Account a2: Trigger.new) {
            if (a2.OwnerId == '00537000000Qsqj') {
                a2.AB_Testing_Autonumber__c = Integer.valueOf(maxlead) + 1;
            } else {
                a2.AB_Testing_Autonumber__c = 1;                                    
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.