Sub topic 1
What happens when Apex code fails
Prerequisites
This chapter assumes you can already do the following:
- Read and write Apex classes, methods, variables, and control flow.
- Run SOQL queries and DML statements such as
insertandupdate. - Describe a transaction and the governor limits at a basic level. A transaction is one unit of work that Salesforce commits or rolls back as a whole.
You do not need any exception-handling knowledge. This chapter builds the model that the rest of the tutorial relies on.
What an exception is
An exception is an object that Apex creates when code reaches a state it cannot continue from. Examples include dereferencing a null variable, assigning an empty query result to a single record, or inserting a record that fails validation. When this happens, normal execution stops at that line. Apex does not run the following statements in that method. It starts looking for code that is prepared to deal with the problem.
Every exception is an instance of a class that extends the built-in Exception class. The class name tells you the category of failure, such as NullPointerException, QueryException, or DmlException. The object also carries a message and a stack trace. Later chapters cover these in detail.
Exceptions are different from compile-time errors. A compile-time error, such as a misspelled variable, stops you from saving the code. An exception only appears at runtime, when a particular line runs with particular data. Code that passes every save check can still throw an exception in production.
How an exception propagates
Methods call other methods, which forms a call stack. When an exception is thrown, Apex checks whether the current method has a catch block that matches the exception type. If it does not, Apex ends that method and checks the method that called it. This repeats up the stack. This movement is called propagation.
If the exception reaches the top of the stack without meeting a matching catch block, it is unhandled. The entry point is whatever started the transaction, such as a trigger, a controller method, or an anonymous Apex script. At that point the transaction ends with an error.
The transaction is rolled back
The most important consequence of an unhandled exception is that Salesforce rolls back the whole transaction. Every DML change made since the transaction started is undone, including changes made by code that ran successfully before the failure. There is no half-saved state.
Here is a small example. Save the class, then run the last line as anonymous Apex.
public class RollbackDemo {
public static void run() {
insert new Account(Name = 'Saved Before Failure');
helper();
}
private static void helper() {
String value = null;
Integer size = value.length();
System.debug('Never reached: ' + size);
}
}RollbackDemo.run();The insert succeeds, then helper dereferences a null string and throws a NullPointerException. Nothing in the call stack catches it, so the transaction fails. After the run, query for an Account named Saved Before Failure. You will not find one. The successful insert was rolled back along with everything else.
Now compare what happens when something catches the exception:
try {
RollbackDemo.run();
} catch (NullPointerException e) {
System.debug('Caught: ' + e.getMessage());
}This time the Account named Saved Before Failure remains in the database. The exception was handled, so the transaction did not fail. Execution continued after the catch block, and the transaction committed normally with the insert included.
This is a design decision, not a detail. Catching an exception means you take responsibility for the state of the data. If the work before the failure should not be saved, you must undo it yourself. Chapter 12 covers savepoints for that.
What the user or developer sees
Where the error appears depends on the entry point.
| Entry point | What happens with an unhandled exception |
|---|---|
| Trigger | The save fails and the user sees an error that names the trigger and includes the exception text. |
| Anonymous Apex | The execution fails, and the error and stack trace appear in the console and the debug log. |
| Aura or Lightning controller method | The client receives a generic error. Your own message appears only for `AuraHandledException`, covered in chapter 13. |
| Queueable, Batch, or Scheduled Apex | The job ends in a failed state, and Salesforce sends an Apex exception email to the configured recipients. |
| Apex REST | The request fails with an error status, and the response body contains the error details. |
Two points apply across all of these.
- The raw message is rarely suitable for end users. Text such as
Attempt to de-reference a null objecttells a sales rep nothing useful. Good error handling turns technical failures into messages people can act on. - The stack trace is for developers. It lists the class, method, and line number for each frame in the call stack, so you can trace the failure to its source. Use the debug log to read it.
Exceptions you can handle and ones you cannot
Almost every exception in Apex can be caught. The main exception to this rule is a governor limit violation. When your code goes over a limit, for example by issuing more than 100 SOQL queries in a synchronous transaction, Apex throws a System.LimitException. You cannot catch it. A catch (Exception e) block will not intercept it. The transaction ends and rolls back no matter what your code does.
The reason is practical. Limits protect the shared platform, so Salesforce does not let code continue after exceeding them. The right defense is to write code that stays within limits, mainly by bulkifying queries and DML. Chapter 11 covers this case.
Other failures are catchable but easy to overlook. Common causes include:
- A
SELECTwith no matching rows assigned to a single record variable, which throws aQueryException. - A call on a variable that holds
null, which throws aNullPointerException. - An
insertorupdatethat violates a validation rule or a required field, which throws aDmlException. - An access to a list index that does not exist, which throws a
ListException.
Reading a failure in the debug log
When a transaction fails, the debug log shows an EXCEPTION_THROWN event where the exception was created. A FATAL_ERROR event appears when it went unhandled. Together they give you the exception type, message, and the stack trace. For example, a failure from RollbackDemo produces a line like this:
System.NullPointerException: Attempt to de-reference a null object
Class.RollbackDemo.helper: line 8, column 1
Class.RollbackDemo.run: line 4, column 1
AnonymousBlock: line 1, column 1Read the trace from the top. The first frame is where the exception occurred, and each later frame is a caller one level up. Here the failure was in helper, which run called, which the anonymous block called.
Why this model matters
Everything in the following chapters builds on three facts from this one.
- An exception stops the current line and moves up the call stack until something catches it.
- If nothing catches it, the whole transaction rolls back.
- If something does catch it, the transaction continues and can commit, including any changes made before the failure.
When you decide whether to catch an exception, you are deciding which of those outcomes you want.
Exercise
A method inserts an Account, then a later line throws a NullPointerException. No code in the call stack has a catch block. Is the Account saved? Would your answer change if the caller wrapped the call in a try block with catch (NullPointerException e) that only logs the message?
Show answer
Without a catch block, the exception is unhandled, so the whole transaction rolls back and the Account is not saved. With the catch block, the exception is handled, the transaction continues, and the Account is committed along with the rest of the transaction. The catch block must undo the insert itself, for example with a savepoint rollback, if the Account should not be saved.
Exercise
Why will catch (Exception e) not prevent a transaction from failing when a synchronous method issues its 101st SOQL query?
Show answer
Exceeding a governor limit throws a System.LimitException, which Apex does not allow code to catch. The transaction ends and rolls back regardless of any catch block. The fix is to write code that stays within limits, not to catch the exception.