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

Not able to send email or insert a record from catch block



I have a requirement to notify a user when there is an error while processing the batch job.


I have written a try catch block in start and execute methods. In the try block, I am inserting a list.

In catch block I tried inserting a record in a generic object named Exception, which has a workflow to send an email to a user.


When i tried this and checked in debug log, I see that the record is created in the Exception object which also gives an Id. But when I go that object and check its not available and when I put the Id which I got in debug log in the URL, its showing as "Data Not available".


I also tried sending mail through the apex email class, there also the same problem. Debug log shows that mail has been sent but I dont get the mail.

When I write the same in finish method, I am getting a mail.

Below is the code I am using:

global Database.QueryLocator start(Database.BatchableContext BC){
    return Database.getQueryLocator(query);
catch(Exception e){
Exception__c objException = new Exception__c();
objException.Description__c = message;
objException.NotifyTo__c = '';//actual mail address here
objException.ExceptionSource__c = source;
objException.User__c = userInfo.getUserId();
objException.EmailSent__c = true;
insert objException;
String recipientAddress = '';
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String textbody = 'There has been an error while processing the job';
String textSubject = 'Job error';
String[] toAddresses = new String[] {recipientAddress};
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


I tried the above(inserting record and sending mail) one after the other and also together. But nothing worked


Please let me know any thoughts




Hi Arvind,

I know this is too old, but i would like to add the answers may be this is useful to new person.
Your dml option in the try catch and error to in the catch block like below:

For Example:-
                 update account;
            } catch (DMLException e){
                 Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
                 String[] toAddresses = new String[] {‘’};
                 mail.setSenderDisplayName(‘Apex error message’);
                 mail.setSubject(‘Error from Org : ‘ + UserInfo.getOrganizationName());
                 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });