+ Start a Discussion
Joe HayesJoe Hayes 

Stop error when SOQL returns 0 results

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"
Best Answer chosen by Joe Hayes
Joe HayesJoe Hayes
I have figured this out, I added to a list and then checked the list.size was > 0.
List<Attachment> attachments = [select name, contenttype, body
                                  from Attachment
                                  where name LIKE '%Venue Information%' 
                                  and ParentId = :cf.courses__r.venueid__c];
        if(attachments.size() > 0){
        Messaging.Emailfileattachment MyMap = new Messaging.Emailfileattachment();
        MyMap.setContentType(attachments[0].contentType);
        MyMap.setFileName('Venue Information.pdf');
        MyMap.setBody(attachments[0].Body);
        fileAttachments.add(MyMap);
        }
     
        mail.setFileAttachments(fileAttachments);