Sub topic 3
What Happens When an Exception Is Not Handled
This chapter assumes you can write basic Apex, run DML (data manipulation language) statements such as insert and update, use try/catch, and know the governor limits exist. It also assumes you know a transaction is the unit of work that Apex either commits or discards as a whole. Here you will learn what Apex does when an exception reaches the top of that transaction without being caught.
The rule
If an exception is not handled, Apex rolls back the entire transaction. No DML from that transaction is saved. This covers every insert, update, delete, and undelete, including the statements that ran successfully before the exception.
"Entire transaction" is broader than the method that threw the exception. It includes every class, trigger, and automation that ran earlier in the same transaction. If a trigger fires from a DML statement and a later line in the calling class throws, the trigger's changes are also discarded.
The platform does the rollback itself. You write no code for it, and you cannot stop it except by catching the exception.
A worked example
The class below inserts an account, confirms the insert is visible inside the transaction, and then throws a custom exception that nothing catches.
public class UnhandledDemo {
public class DemoException extends Exception {}
public static void insertThenFail() {
insert new Account(Name = 'Unhandled Demo');
Integer inside = [SELECT COUNT() FROM Account WHERE Name = 'Unhandled Demo'];
System.debug('Inside the transaction: ' + inside);
throw new DemoException('Failing after the insert');
}
}Run it from Anonymous Apex:
UnhandledDemo.insertThenFail();The debug log shows Inside the transaction: 1, because a query in the same transaction can see its own uncommitted DML. Then the run ends with an unhandled UnhandledDemo.DemoException. Now run a second, separate execution:
System.debug([SELECT COUNT() FROM Account WHERE Name = 'Unhandled Demo']);It prints 0. The first execution was one transaction, and the exception caused the platform to discard the insert.
The finally block does not rescue DML
A finally block runs even when an exception is in flight. That does not make its DML permanent. The transaction is still rolled back when the exception goes unhandled.
public class FinallyDemo {
public class DemoException extends Exception {}
public static void run() {
try {
insert new Account(Name = 'Finally Demo Account');
throw new DemoException('Unhandled after finally');
} finally {
insert new Account(Name = 'Finally Demo Log');
System.debug('finally block ran');
}
}
}The debug log contains finally block ran, so the second insert executed. After the run, a query for either account returns nothing. Both inserts were part of the failed transaction.
The same applies to a catch block that rethrows. If you catch an exception, write a log record, and then throw e, the log record is rolled back along with everything else. Writing an error log that survives needs a mechanism outside the transaction, such as a platform event that publishes immediately. Plain DML won't do it.
Exceptions you cannot catch
Some failures cannot be handled. System.LimitException, thrown when you exceed a governor limit, is the main case. A catch (Exception e) block does not intercept it. Apex ends the transaction and rolls it back.
try {
for (Integer i = 0; i < 200; i++) {
insert new Account(Name = 'Loop Account ' + i); // DML inside a loop
}
} catch (Exception e) {
System.debug('This line is never reached for a limit exception');
}The 151st insert exceeds the limit of 150 DML statements per transaction. The run fails with System.LimitException: Too many DML statements: 151, and the catch block does not run. The first 150 accounts are rolled back as well, so you end up with none of them. A learner often expects "150 saved, then an error", but Apex does not behave that way.
Because limit exceptions cannot be caught, you cannot use a savepoint, a later topic, to recover from one inside the same transaction. The fix is to stay under the limits, for example by moving the insert outside the loop and inserting a list once.
What the user or caller sees
The rollback is the same everywhere. What differs is how the failure is reported and how much work counts as "the transaction".
| Entry point | Result of an unhandled exception |
|---|---|
| Anonymous Apex | The execution fails and the error appears in the output and log. All DML is rolled back. |
| Trigger | The DML statement that fired the trigger fails. The user or API caller gets the error, and the changes are rolled back. |
| Lightning or Visualforce controller | The error goes back to the page. Changes made during that request are rolled back. |
| Batch Apex `execute` | Only the current batch of records is rolled back. Earlier batches stay committed, and later batches still run. |
| Queueable or `@future` method | That job fails and its DML is rolled back. |
The batch row is the one that most often surprises people. Each call to execute is its own transaction, so an exception in the third batch does not undo the first two. A later chapter on asynchronous Apex covers this further.
What is not undone
A rollback restores the database. It does not restore everything your code touched.
- Callouts that already completed. The remote system has received the request, and Apex cannot call it back.
- Static variables and other in-memory values. They keep whatever value they had when the exception occurred, for the rest of the transaction.
- Id values on sObjects you inserted. The row is gone, but the in-memory record still holds its Id. A later chapter shows how to handle this.
If your logic depends on any of these, do not assume a failed transaction left them clean.
Common mistakes
- Assuming that DML before the
throwis kept. It is kept only if the exception is caught, which the next chapter covers. - Putting cleanup or logging DML in
finallyand expecting it to persist after an unhandled exception. - Wrapping a loop of DML in
catch (Exception e)and expecting it to absorb aLimitException. - Testing the rollback in the same transaction. A query in the same execution still sees the uncommitted records, as the
Inside the transaction: 1line showed. Verify in a separate execution, or in a test method, which a later chapter covers.
Summary
- An unhandled exception rolls back all DML in the current transaction, without any code from you.
- The scope is the whole transaction, not just the method that threw.
finallyblocks run, but their DML is rolled back too.- Limit exceptions cannot be caught and always roll back the transaction.
- Callouts, static variables, and in-memory Ids are not reverted.
Exercise
A method inserts an Account, then inserts a Contact whose required field is missing, which throws a DmlException. The caller does not catch it, and a finally block in the method inserts a second Account named 'Audit'. After the transaction ends, which of the two Accounts exist in the database, and why?
Show answer
Neither exists. The DmlException is unhandled, so the whole transaction is rolled back. The finally block ran, but its insert was part of the same transaction and was discarded with the rest.
Exercise
A loop performs one insert per iteration and runs 200 times inside a try block with catch (Exception e). What happens at the 151st iteration, and how many of the Accounts are saved?
Show answer
Apex throws a System.LimitException (Too many DML statements: 151). It cannot be caught, so the catch block does not run, and the transaction is rolled back. No Accounts are saved. The fix is to collect the records in a list and insert it once, outside the loop.