[SalesForce] Execute Anonymous Error :- System.ListException: List index out of bounds: 0

While Updating the Custom Object(SiteContracts__c) fields through Execute Anonymous I am getting this Error.
Here is my code:

List<SiteContracts__c> sitecontractList = new List<SiteContracts__c>();

  sitecontractList = [SELECT Id,X6L_Water__c,field1__c.field2__c(Select id,visit__r.visit_type__c,visit__c,X6L_Water_Qty__c,field1__c,field2__c,
                      Site_Contract__c,Service_Sheet_Type__c from Service_Sheets__r
                       WHERE Fire_Extinguisher_Service_complete__c=True ORDER BY createdDate DESC LIMIT 1) FROM SiteContracts__c];

Engineer_Checklist__c tempSS;
Boolean check;
if(sitecontractList.size()>0){
for(SiteContracts__c siteContract:sitecontractList) {
    tempSS=siteContract.Service_Sheets__r[0];
    check=false;
    if((tempSS.visit__r.Visit_Type__c=='Service Revisit FOC'|| tempSS.visit__r.Visit_Type__c=='Service Revisit') 
                                    && tempSS.Service_Sheet_Type__c=='Fire Extinguisher' )
    {
        check=true;
    }
         siteContract.X6L_Water__c=(check?(siteContract.X6L_Water__c==NULL?0:siteContract.X6L_Water__c)+(tempSS.X6L_Water_Qty__c==NULL?0:tempSS.X6L_Water_Qty__c):tempSS.X6L_Water_Qty__c);
             siteContract.X6L_Water__c=(siteContract.X6L_Water__c==0?tempSS.X6L_Water_Qty__c:siteContract.X6L_Water__c);

 siteContract.field1__c=(check?(siteContract.field1==NULL?0:siteContract.field1__c)+(tempSS.field1==NULL?0:tempSS.field1__c):tempSS.field1__c);
             siteContract.field1__c=(siteContract.field1__c==0?tempSS.field1:siteContract.field1__c);

 siteContract.field2__c=(check?(siteContract.field2__c==NULL?0:siteContract.field2__c)+(tempSS.field2__c==NULL?0:tempSS.field2__c):tempSS.field2__c);
             siteContract.field2__c=(siteContract.field2==0?tempSS.field2__c:siteContract.field2__c);
 }
  update sitecontractList;       
}

I Checked the Query in Query Editor and it retrieved the values. but I don know what is wrong in my code. Can anyone help me.
Thanks in advance.

Best Answer

Judging from the errormessage, t must be occurring in this line:

tempSS=siteContract.Service_Sheets__r[0];

So the error means that for the particular siteContract that the code is looking at in that iteration, the Service_Sheets__r list is empty.

You'd need to check for that first:

if(!siteContract.Service_Sheets__r.isEmpty()){
   // do the actions
}   
Related Topic