I have a controller that sends an email and grabs a few different attachments from different records.

Not all the records will have an attachment called 'Venue Map' so I want to stop the error if the SOQL returns null. Not sure what to do here.

    Attachment att = [
         select name, contenttype, body
         from Attachment
         where name LIKE '%Venue Map%' and ParentId = :cf.courses__r.venueid__c][0];

    if(att.body.size() > 0 ){
    Messaging.Emailfileattachment MyMap = new 
    Messaging.Emailfileattachment();
    MyMap.setContentType(att.contentType);
    MyMap.setFileName('Venue Information.pdf');
    MyMap.setBody(att.Body);
    fileAttachments.add(MyMap);
    }     

    mail.setFileAttachments(fileAttachments);

The code is working perfect when there is a 'Venue Map' attachment, but if there isnt it just gives me this error "List index out of bounds: 0"

up vote 2 down vote accepted

I suggest before using indexing of [0]. first, query and store into the list and then check if the size is more than 0 then perform everything like below

List<Attachment> attachments = [select name, contenttype, body
                                  from Attachment
                                 where name LIKE '%Venue Map%' 
                                   and ParentId = :cf.courses__r.venueid__c];
if(attachments.size() > 0){
    att = attachments[0];

   if(att.body.size() > 0 ){
       Messaging.Emailfileattachment MyMap = new 
       Messaging.Emailfileattachment();
       MyMap.setContentType(att.contentType);
       MyMap.setFileName('Venue Information.pdf');
       MyMap.setBody(att.Body);
       fileAttachments.add(MyMap);
   }     

    mail.setFileAttachments(fileAttachments);
}
  • @JoeHayes your welcome – Ratan Paul Aug 10 at 10:11

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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