0

This NOT a trigger. This is a VF page controller.

I think you should use try-catch blocks but I'm not sure whats the best practice for that.

Should I put in all the code in the try block? Like this :

try{
    insert A;
    A__c.Name__c = 'jkl';
    update A;
}
catch(DmlException e){
    System.debug('The following exception has occurred: ' + e.getMessage());
}

Or write the update after the entire try-catch block? Like this :

try{
    insert A;
}
catch(DmlException e){
    System.debug('The following exception has occurred: ' + e.getMessage());
}

A__c.Name__c = 'jkl';
    update A;

2 Answers 2

0

In first block if you get any exception then the complete transaction will not be roll back. That part where exception is occur will be roll back.

try
{
    account acc = new account( name = 'dsnfcknfo');
    insert acc;
    system.debug('##########'+acc.id);
    contact c = new contact(lastname = null);
    insert c;
}
catch(Exception e){}

I run this code and Account created successfully where in contact I must get an exception which I have skipped.

enter image description here

In second block if you get any exception in Account insert then A__c will still update. If you get any exception in A__c then as you don't handle that so you will get exception on UI. Also it will revert back the Account insert process as well.

try
{
    account acc = new account( name = 'dsnfcknfo');
    insert acc;
    system.debug('##########'+acc.id);

}
catch(Exception e){}
contact c = new contact(lastname = null);
    insert c;

Then First I got exception but when I check debug I get Account Id.

enter image description here

But when I try to access this record does not exist so the complete transaction will be revert back.

So if you want to revert the complete transaction then second Option otherwise you should go with first option.

Also in first option if you want to roll back the complete transaction then you can Database.Savepoint

3
  • In the second case, it shouldn't update as well I think...
    – Lance Shi
    Nov 22, 2016 at 7:09
  • If I want to ONLY update A__c if it has been inserted before, I should use the first version, correct? Also, in both cases, shouldnt the update fail in 2nd case too? Because in the 2nd case, if the exception happens, it will stop execution and it wont reach the line where A__c is updated?
    – fraglord
    Nov 22, 2016 at 7:12
  • @fraglord if in second case exception occur in Account insert then it will update A__c without any issue. Also I have updated my answer with more detail. Nov 22, 2016 at 7:18
0
    try{
    Upsert A;
    A__c.Name__c = 'jkl';
    upsert A;
}
catch(DmlException e){
    System.debug('The following exception has occurred: ' + e.getMessage());
}
1
  • Use Upsert instead of Insert for insert and update operations. Nov 22, 2016 at 7:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .