+ Start a Discussion
Nisha WarrierNisha Warrier 

Apex Transaction

As I understand, a transaction boundary can be a trigger, a method , anonymous block etc.If I have more than one DML opns in same method, 2 insert operations and if one of them throws an exception, the entire DML operations in that method (boundary) should be rolled back .I was trying this out with 2 simple insert operations.
Account and Lead.Following is the code.It is jsut a sample one and this is not a realistic situation.
public class TransactionCheck {

    public static void insAndUpd(){
        for(integer i=1;i<=3;i++){
                Account acn=new Account(Name='ABC Account '+i);
                insert acn;
                System.debug(i+'th Account inserted');
                Lead newLead=new Lead();
                insert newLead;
            catch(DMLException de){
                System.debug('Caught you!!  '+de);

Here, each time I call the method from anonymous block, if there is no exception, it should insert accounts as ABC Account 1, ABC Account 2, ABC Account  3 .I purposely created the lead without any data  so that it can throw an exception (Missing field)...
So the ouput what I am expecting is the first debug statement should work saying 1th Account inserted (all the time ).But due to exception,the transaction should be rolled back and no accounts should be inserted rt?
But they are getting inserted everytime .Attaching the log and my page.Plz correct me if I am wrong...User-added imageUser-added image
Naval Sharma4Naval Sharma4
Hi Nisha,

I am doubting that these records are inserted from the code which you executed from developer console. Can you change account name in your code and re-execute this code?

If you want to know about transaction which get excuted successfully then refer to debug logs.

User-added image
Nisha WarrierNisha Warrier
Hi Naval,
Ya , I have executed the code using anonymous block.The logs attached are from debug logs. I tried with 3-4 different names.Is there any restriction that ony Database.insert will be considered as a part of transaction?