Sub topic 7
Catching an Exception Does Not Undo Earlier DML
This chapter assumes you can write basic Apex, run DML statements such as insert and update, and use try/catch with DmlException. It also assumes you know that Apex enforces governor limits. The previous chapter showed that an unhandled exception rolls back the whole transaction. This chapter covers what happens when you handle the exception.
The rule
A transaction ends in one of two ways. It ends with an unhandled exception, and Salesforce rolls back all of its changes. Or it ends normally, and Salesforce commits them. A catch block turns the first case into the second. After the catch, execution continues. If nothing else fails, the transaction commits, including every DML statement that succeeded before the exception.
Catching an exception stops it from propagating. It does not undo anything. The database changes made by earlier statements stay in place.
A caught exception leaves earlier DML in place
insert new Account(Name = 'Kept');
try {
insert new Account(); // Name is required, so this throws a DmlException
} catch (DmlException e) {
System.debug(e.getMessage());
}
// The exception was handled, so the first Account is still committed when the transaction ends.
System.debug([SELECT COUNT() FROM Account WHERE Name = 'Kept']);Three things happen here:
- The first
insertsucceeds. The row is pending in the transaction. - The second
insertfails with aREQUIRED_FIELD_MISSINGerror. That one statement saves nothing, because a single DML statement is all-or-none. The exception goes to thecatchblock. - The script finishes normally. The transaction commits, and
Keptis saved.
The SELECT COUNT() at the end returns at least 1. That shows the pending row is visible inside the transaction. It does not show that the row is committed. The commit happens when the transaction ends.
The failed statement versus the statements before it
A failed statement and the work around it are separate things:
- The failed statement saves none of its own records when it uses default all-or-none behavior.
- Statements that completed before it are not touched.
- Statements that run after the
catchblock still execute and still save.
Treating a catch block as "undo what I just tried" is the common mistake. It only means "I have dealt with the error."
How this produces half-finished data
The risky case is a parent record saved by one statement and a child record saved by the next.
Account acct = new Account(Name = 'Orphan Risk');
insert acct;
try {
insert new Contact(AccountId = acct.Id); // LastName is required
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, 'Contact insert failed: ' + e.getMessage());
}
System.debug([SELECT COUNT() FROM Account WHERE Name = 'Orphan Risk']);The error is logged, and the code looks defensive. But the Account is saved with no Contact. If your business rule says every new Account needs a Contact, you have just committed data that breaks it. The exception was handled, but the transaction is no longer consistent.
Getting a rollback after catching: rethrow
If you need to log or clean up and still want the transaction undone, rethrow the exception. An exception that leaves your code unhandled reaches the transaction boundary and triggers the rollback.
public with sharing class AccountService {
public static void createWithContact(String accountName, String lastName) {
Account acct = new Account(Name = accountName);
insert acct;
try {
insert new Contact(LastName = lastName, AccountId = acct.Id);
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, 'Contact insert failed: ' + e.getMessage());
throw e;
}
}
}Calling AccountService.createWithContact('Acme', null) from anonymous Apex fails with an unhandled DmlException. Salesforce then rolls back the whole transaction, so the Account is not saved either.
You can also throw a different exception type from the catch block. In an @AuraEnabled method, for example, you throw AuraHandledException so the client gets a readable message. As long as the exception leaves the entry point unhandled, the rollback happens.
Rethrowing only works if nobody upstream catches it
Rethrowing does not guarantee a rollback. It only passes the problem to the caller. If the caller catches it, you are back in the same situation:
try {
AccountService.createWithContact('Acme', null);
} catch (DmlException e) {
System.debug('Caller handled it: ' + e.getMessage());
}
// The Account from createWithContact is still pending and will be committed.The Account inserted inside createWithContact survives, because the outer catch handled the exception. A transaction rolls back only when an exception reaches the top unhandled. The depth of the call stack does not matter, and no inner method can undo the work of an earlier one on its own. Keep this in mind when you write a service method that other code calls. You cannot know whether the caller will catch.
Handled exceptions do not protect you from later failures
The reverse also holds. A transaction is one unit, so an unhandled exception anywhere rolls back everything, including work that was followed by a handled exception earlier.
insert new Account(Name = 'Rolled Back Later');
try {
insert new Account(); // handled
} catch (DmlException e) {
System.debug('Handled: ' + e.getMessage());
}
insert new Contact(); // LastName missing, unhandledThe final insert throws an unhandled DmlException. The whole transaction rolls back, and Rolled Back Later is not saved. The earlier catch did nothing to protect it.
Exceptions you cannot catch
Some failures cannot be handled in Apex. A System.LimitException, such as exceeding the DML statement limit or the CPU time limit, cannot be caught. A catch (Exception e) block will not stop it. The transaction ends and rolls back. So a limit failure undoes your earlier work even when you wrapped everything in a catch block.
Summary by scenario
| Scenario | Earlier successful DML |
|---|---|
| Exception thrown and never caught | Rolled back |
| Exception caught, execution continues, no later failure | Committed |
| Exception caught and rethrown, nobody upstream catches it | Rolled back |
| Exception caught and rethrown, a caller catches it | Committed |
| Exception caught, but a later unhandled exception occurs | Rolled back |
| `LimitException` | Rolled back, and it cannot be caught |
Common mistakes
- Assuming that a catch block restores the database to its state before the
try. It restores nothing. - Logging the error in
catchand returning a success message to the user while earlier records stay saved. - Catching
Exceptionbroadly around a multi-step operation, which hides failures that should have stopped the transaction. - Relying on rethrow for atomicity in a method that other code calls, without checking whether callers catch.
- Assuming a
LimitExceptioncan be recovered from.
What to do when you want to keep going but undo part of the work
Sometimes you want to handle the error and also remove the work that belongs with the failed step. Rethrowing is too blunt, because it ends the whole transaction. For this you need to mark a point in the transaction and return to it. Apex provides savepoints for this, covered in the next chapters.
Exercise
An anonymous Apex script inserts an Account named 'One'. It then inserts an Account with no Name inside a try block and catches the DmlException. After the catch block it inserts an Account named 'Two'. Nothing else fails. Which Accounts exist after the script finishes, and why?
Show answer
'One' and 'Two' exist. The failing insert saved nothing, because a single DML statement is all-or-none. The catch block handled the exception, so the transaction continued and committed normally. Statements before and after the catch are unaffected.
Exercise
A service method inserts an Account, catches a DmlException from a Contact insert, logs it, and rethrows it with "throw e". A caller wraps the service call in its own try/catch that logs and continues. Is the Account saved when the transaction ends?
Show answer
Yes. The rethrown exception was caught by the caller, so it never reached the transaction boundary unhandled. The transaction commits, including the Account. Only an exception that propagates out of the entry point unhandled causes a rollback.