I have created a trigger to populate some address information according to record type. I have included try catch block to handle the exception. To check whether the exception handling working or not , I created an exception. Even though there is exception the auto population of the fields works. How is it possible???

trigger AutoPopulateAccountAddressFields on Account (before insert,before update) {
List<Error_Log__c> log = new List<Error_Log__c>{};
    List<Account> accList = new List<Account>{};

    for(Account acc :Trigger.new){

    for(Account acc :accList){

        if(acc.RecordTypeId == '01290000000XLCu'){
          acc.BillingStreet='Door Way';
    update accList;  //This line causes an exception
catch(Exception ex){
    Error_Log__c accErr = new Error_Log__c();
    accErr.Error_Message__c = ex.getMessage();
    accErr.Object_Name__c = 'Account';

insert log;
  • what exception are you catching? Are you getting to the catch block? I think you should be use the .adderror method to prevent the DML operations – Prady Dec 31 '13 at 7:39
  • Apex passes variables by reference. even if update statement fails, accounts in Trigger.New have been updated. The Trigger.New will be persistent along with modifications done. – Ganesh Bhosle Dec 31 '13 at 7:40
  • @Prady How can I add '.addError' to the record that causing the exception. Is it possible to get the recordId inside the catch block? – arabisays Dec 31 '13 at 9:34
  • Don't update records in a before update trigger that are already involved in the before update trigger, because you'll hit an infinite recursion problem anyways. Just apply the values and forget-about-it. Changes made to Trigger.new automatically persist if the trigger completes. – sfdcfox Dec 31 '13 at 15:38

As you are in a before trigger and your acclist contains the elements from trigger.new, any changes you make to those records will be applied when the trigger completes.

I'd imagine the DML exception you are getting is that you can't execute an update on records that are in trigger.new. You are catching this exception and handling it, so the trigger then continues and the changes you make are persisted to the database.

In order to unwind the changes, you'd need to clone the trigger.new records and in your catch block change them back to their state when the trigger started.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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