Sub topic 1
Exception Handling and Custom Exceptions in Apex
Prerequisites
Assume you know basic Apex classes, methods, control flow, SOQL, DML, and Salesforce transactions.
What happens when Apex code fails
An exception is a runtime error that interrupts normal execution. Apex creates an exception object and looks for a matching catch block. If no matching block exists, the exception propagates to the caller. If it reaches the top of the transaction, the transaction fails and uncommitted database work is rolled back.
Handling errors with try, catch, and finally
Put code that might fail in try. A catch block handles a specific exception type. The finally block runs whether the operation succeeds or fails, so use it for cleanup or consistent logging.
try {
Account accountRecord = [
SELECT Id
FROM Account
WHERE Name = 'Does Not Exist'
LIMIT 1
];
System.debug(accountRecord.Id);
} catch (QueryException e) {
System.debug('Query failed: ' + e.getMessage());
} finally {
System.debug('Finished account lookup.');
}Common built-in exception types
| Exception | Typical cause |
|---|---|
| `QueryException` | A SOQL query assigned to one record returns no record |
| `DmlException` | An insert, update, or delete fails |
| `NullPointerException` | Code accesses a null value |
| `ListException` | Code uses an invalid list index |
Reading exception details
Exception methods help diagnose failures:
getMessage()returns the error message.getTypeName()returns the exception type.getCause()returns an underlying exception when one exists.getStackTraceString()returns the call stack.
Log these details carefully. Messages and stack traces can expose information that should not be shown to end users.
> callout note > Catch an exception only when you can handle it, add useful context, or translate it for another layer. Otherwise, let it propagate.
Multiple catch blocks and the generic Exception
When several handlers are needed, put specific exception types before the general Exception type. Exception matches many errors, so placing it first prevents later handlers from being reached.
try {
insert new Account();
} catch (DmlException e) {
System.debug('DML error: ' + e.getMessage());
} catch (Exception e) {
System.debug(e.getTypeName() + ': ' + e.getMessage());
}Exercise
Why must a DmlException catch block appear before an Exception catch block?
Show answer
Exception is more general and would match the DmlException first, making the specific handler unreachable.