Sub topic 2
Handling errors with try, catch, and finally
This chapter assumes you can write basic Apex classes and methods, run SOQL queries and DML statements, and know that a transaction is a unit of work that Salesforce either commits or rolls back. Here you will learn how the three blocks of a try statement work together, and how they change what happens to your transaction.
What the three blocks do
A try statement has up to three parts:
tryholds the code that might fail.catchholds code that runs only if a matching exception is thrown inside thetryblock.finallyholds code that runs every time, whether or not an exception occurred.
You need at least one catch or one finally with every try. You can use a try with only a finally, or with only catch blocks.
try {
Account a = [SELECT Id FROM Account WHERE Name = 'Does Not Exist' LIMIT 1];
System.debug(a.Id);
} catch (QueryException e) {
System.debug('Query failed: ' + e.getMessage());
} finally {
System.debug('This runs whether or not an exception occurred.');
}Assigning a query that returns no rows to a single Account variable throws a QueryException. The statement System.debug(a.Id) never runs. Execution jumps to the matching catch block, then to finally, and then continues after the whole statement.
The catch parameter (e here) is a local variable with the exception type you declared. The block only runs if the thrown exception is that type or a subclass of it.
The flow of control
The diagram shows the possible paths through a try statement.
Notice that finally runs on every path, including the one where no catch block matches. In that case the exception continues up the call stack after finally finishes.
What happens to the rest of the try block
Once an exception is thrown, the remaining statements in the try block are skipped. This matters when you have several operations in a row.
try {
insert new Account(Name = 'First');
insert new Account(); // throws DmlException: Name is required
insert new Account(Name = 'Third'); // never reached
} catch (DmlException e) {
System.debug('Stopped early: ' + e.getMessage());
}The third insert never runs. If you want to keep going after a failure, put each risky operation in its own try, or use the Database methods with partial success (covered in a later chapter).
A caught exception does not roll back earlier work
This is the most common surprise at the intermediate level. Compare two cases:
- An exception is thrown and not caught by any code in the transaction. Salesforce rolls back all DML in the transaction and reports the error.
- An exception is thrown and caught. The transaction continues, and Salesforce commits it at the end, including DML that succeeded before the failure.
Account first = new Account(Name = 'Saved Anyway');
insert first;
try {
insert new Account();
} catch (DmlException e) {
System.debug('Caught: ' + e.getMessage());
}
// The first insert is still pending and will be committed.
System.debug([SELECT COUNT() FROM Account WHERE Name = 'Saved Anyway']);Catching an exception means you have decided the error is handled. If the earlier work should be undone, you must undo it yourself with a savepoint, or rethrow the exception. Savepoints get their own chapter.
Using finally
Use finally for cleanup that must happen regardless of outcome. Apex has no open files or connections to close, so typical uses are resetting static state and writing diagnostic information.
public class TriggerGuard {
public static Boolean skipTriggers = false;
public static void updateWithoutTriggers(List<Account> accts) {
skipTriggers = true;
try {
update accts;
} finally {
skipTriggers = false;
}
}
}Here the flag is reset even if update throws. There is no catch, so the exception still propagates to the caller after the flag is reset. That is a legitimate pattern: clean up, but let someone else decide how to handle the error.
finally and return
finally runs even when the try block returns.
public class FinallyDemo {
public static String run() {
try {
return 'from try';
} finally {
System.debug('finally runs before the method returns');
}
}
}The debug line is written, then the caller receives 'from try'. Avoid putting a return inside finally. It makes the flow hard to follow, and it is not worth the confusion.
Exceptions inside catch and finally
A catch block is ordinary code, and it can throw. An exception thrown in catch is not caught by sibling catch blocks of the same statement. It propagates outward, after finally runs.
try {
try {
Integer x = 1 / 0;
} catch (MathException e) {
throw new StringException('Rethrown as a different type');
} finally {
System.debug('inner finally');
}
} catch (StringException e) {
System.debug('outer catch: ' + e.getMessage());
}The output order is inner finally, then outer catch: Rethrown as a different type. The inner catch handled the MathException by throwing a new exception, and the outer try caught that one.
If finally itself throws, that new exception replaces any exception that was already in flight. The original error is lost, so keep finally blocks simple and unlikely to fail.
Scope of variables
A variable declared inside try is not visible in catch or finally. Declare it before the try if you need it afterwards.
Savepoint sp = Database.setSavepoint();
Integer processed = 0;
try {
for (Account a : [SELECT Id FROM Account LIMIT 10]) {
a.Description = 'Reviewed';
update a;
processed++;
}
} catch (DmlException e) {
System.debug('Failed after ' + processed + ' records');
} finally {
System.debug('Processed: ' + processed);
}processed is declared outside the try, so both catch and finally can read it. This example puts DML in a loop only to demonstrate scope. In real code, collect the records into a list and run one update after the loop to stay within governor limits.
What try/catch cannot do
Some failures cannot be caught. Exceeding a governor limit, such as too many SOQL queries, throws a LimitException that no catch block can handle, and the transaction ends. A finally block does not rescue you either, and a later chapter covers this. For now, remember that try and catch are for errors your code can reasonably recover from or report.
Practical guidelines
- Keep the
tryblock small. Wrap only the statements that can throw the exception you expect, so you do not catch errors from unrelated code. - Catch specific types. Catching a broad type can hide bugs, a topic the chapter on catch order covers.
- Decide on every catch: recover, log and continue, or rethrow. Writing the decision down in a comment helps the next reader.
- Use
finallyfor cleanup, not for business logic.
Exercise
A method contains a try block that ends with return 1; and a finally block that calls System.debug('cleanup'). No exception is thrown. Does the debug statement run, and what does the caller receive?
Show answer
Yes, the debug statement runs. The finally block executes before the method actually returns, and the caller receives 1.
Exercise
In one transaction, your code inserts a valid Account, then runs insert new Account(); inside a try block with a catch for DmlException that only logs the message. The transaction then finishes normally. Is the valid Account saved? Why, and how could you make the whole transaction undo it?
Show answer
Yes, it is saved. The exception was caught, so Salesforce treats the transaction as successful and commits the first insert. To undo it, set a savepoint before the first insert and call Database.rollback in the catch block, or rethrow the exception so it is uncaught and the platform rolls back the whole transaction.