function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Error Exception Handling


I am looking for a little boost on an issue I am having.  I am calling the code snippet below from another class that is Batch Apex.  The results from the batch job do not show as failing nor does the log show that I have a failure.  However, when I intentionally make a field smaller than the data that I am inserting the INSERT fails.  I had to dig into several of the logs returned from the batch process to find that the insert InsertList line below is failing.  So my error handling is working to report the message in the log but if this was in production I would not have any clue that it failed.  In addition, I never received the automated email that SF usually sends me that Apex code failed (User setting is turned on).


Should I do my try catch block at the caller level that is inside the batch apex class?  Or is there something that I am doing wrong.  I thought if you catch an error and do nothing like the code below is doing that the reset of the code would stop.  At the end of the job no records where update or insert by any of my other code so I believe it all was rolled back.




    public static Integer InsertErrorRecycle(List<Enrollment_Recycle__c> InsertList) {
         try {
             insert InsertList;
             System.debug('Enrollment_QueryBase.InsertErrorRecycle insert count: ' + InsertList.size());
         } catch(System.DmlException e) {
            System.debug('DmlException in Enrollment_QueryBase.InsertErrorRecycle: Error at line ' + e.getLineNumber() + ' - ' + e.getMessage());
         } catch(System.Exception e) {
            System.debug('Exception in Enrollment_QueryBase.InsertErrorRecycle: Error at line ' + e.getLineNumber() + ' - ' + e.getMessage());
         return InsertList.size();        


Best Answer chosen by Admin (Salesforce Developers) 

Since you are catching the exception you need to handle it in you code. if you remove the try , catch block from the code the exception will be handle by SFDC, the batch will stop, and you will get notified via email.


You can send an email to yourself from the catch block with the data you need like so:


Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setToAddresses(new String[] {''});
mail.setSenderDisplayName('Salesforce Batch');
mail.setSubject('Batch Fail');
mail.setHtmlBody ('Exception in Enrollment_QueryBase.InsertErrorRecycle: Error at line ' + e.getLineNumber() + ' - ' + e.getMessage());
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });