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 the unit of work Salesforce commits or rolls back together. Here you learn how to intercept an exception before it ends the transaction.
The working model
When Apex throws an exception that nothing catches, the transaction stops and all its uncommitted database changes roll back. A try block marks code that might fail. Apex runs a matching catch block if an exception occurs. A finally block runs afterward either way.
A first example
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. Execution jumps out of the try block at that line, so System.debug(a.Id) never runs. The catch block receives the exception in the variable e, and finally runs last.
If the query found a row, the catch block would be skipped. The finally block would still run.
The rules of each block
- A
tryblock needs at least onecatchor afinally. It can have both. - A
catchblock names the exception type it handles and a variable for the exception. It runs only when the thrown exception is that type or a subclass of it. - A
finallyblock has no parameters. Use it for cleanup that must always happen, such as resetting a static flag. - Variables declared inside
tryare not visible incatchorfinally. Declare them before thetryif you need them later.
What happens when no catch matches
If the exception type does not match any catch block, Apex still runs finally. The exception then propagates to the calling method. This continues up the call stack until something catches it or the transaction ends with an unhandled exception.
public class Demo {
public static void run() {
try {
Integer x = 1 / 0;
} catch (QueryException e) {
System.debug('Not reached: wrong type');
} finally {
System.debug('Cleanup still runs');
}
}
}Dividing by zero throws a MathException. The QueryException catch does not match, so only the finally message prints, and the caller of Demo.run() receives the MathException.
Common errors
- Catching and ignoring. An empty
catchblock hides the failure. The transaction continues in an unknown state, and nobody learns that something broke. At minimum, loge.getMessage()or rethrow. - Putting too much in one try. A large
trymakes it hard to know which statement failed. Wrap only the statements that can throw the exception you plan to handle. - Returning from finally. Avoid logic in
finallythat could itself throw, because it can mask the original exception.
Exercise
A try block contains an insert followed by System.debug('done'). The insert throws a DmlException, and the only catch block handles QueryException. There is also a finally block. Which of these run: the debug statement, the catch block, the finally block? What happens to the exception?
Show answer
Only the finally block runs. The debug statement is skipped because execution leaves the try block at the failing insert. The catch block does not match, since DmlException is not a QueryException. After finally runs, the DmlException propagates to the caller, and if nothing catches it the transaction rolls back.