+ Start a Discussion
john.krjohn.kr 

System.ListException: List index out of bounds: 0

I am getting error "System.ListException: List index out of bounds: 0 "when run the testmethod.whats the meaning of that and how can i resolved.

 

List<custom obj__c> lrecords=[
                       select Id,name,
                              from custom obj__c   
                 ];

 lrecords[0].Fileld1__c = 2;
            lrecords[0].Fileld2__c =3;
            update lrecords;

 

If i comment "lrecords[0].Fileld1__c = 2;  lrecords[0].Fileld2__c =3; " this lines no error.what is the issue on this.

Thanks in advance

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

This means that your query has returned no records that match the criteria.  If you then attempt to access an element at row 0, this will throw an error as that row doesn't exist.

 

Its good practice to check there are records first:

 

List<custom obj__c> lrecords=[
                       select Id,name,
                              from custom obj__c   
                 ];

if (lrecords.size()>0)
{
   lrecords[0].Fileld1__c = 2;
            lrecords[0].Fileld2__c =3;
            update lrecords;
}