Sub topic 3
Catching DmlException when a statement fails
This chapter assumes you can write Apex classes and methods, use try/catch, and know that Apex runs in a transaction with governor limits. It covers what a DML statement does when a record fails, and how to read the DmlException it throws.
What happens when a statement fails
A DML statement such as insert, update, upsert, delete, or undelete is all-or-nothing. If any record in the operation fails, Apex does two things:
- It rolls back every record in that statement, including records that were valid.
- It throws a
DmlException.
If nothing catches the exception, the whole transaction fails and all earlier DML in it is rolled back as well.
A first example
The second account has no Name, which is a required field, so the insert fails.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account() // Name is required, so this record fails
};
try {
insert accounts;
} catch (DmlException e) {
System.debug('Failed rows: ' + e.getNumDml());
System.debug(e.getMessage());
}Neither account is saved. The valid Acme record is rolled back along with the invalid one. getMessage() gives one combined text, which is fine for a log line but hard to act on in code.
Reading the details per record
DmlException has methods that describe each failed row. getNumDml() returns how many failures the exception reports. For each index from 0 up to that count, you can ask for details:
| Method | Returns |
|---|---|
| `getDmlIndex(i)` | Position of the failed record in the input list |
| `getDmlStatusCode(i)` | A status code string such as `REQUIRED_FIELD_MISSING` |
| `getDmlMessage(i)` | The human-readable message for that row |
| `getDmlFieldNames(i)` | A list of the fields involved in the error |
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account()
};
try {
insert accounts;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug(
'Row ' + e.getDmlIndex(i) + ': ' +
e.getDmlStatusCode(i) + ' - ' +
e.getDmlMessage(i) + ' ' +
e.getDmlFieldNames(i)
);
}
}Use the status code for branching logic, because messages can change wording. Use the message for logs or user feedback.
Common mistakes
- Catching too broadly.
catch (Exception e)also hides unrelated bugs such as null pointer errors. CatchDmlExceptionwhen you mean to handle DML failures. - Assuming the valid records were saved. With a statement, they were not. If you need the valid ones to save, the statement is the wrong tool, and a Database method with
allOrNoneset to false fits better. A later chapter covers it. - Swallowing the error. An empty
catchblock leaves the user with no record and no message. Log the error, surface it, or rethrow it. - Expecting to catch limit errors. Exceeding a governor limit, such as too many DML statements, throws a
LimitException. You cannot catch that exception.
Rethrowing for callers
In a service class, you often want to add context and let the caller decide what to do. Here the method wraps the failure in a custom exception.
public class AccountService {
public class AccountServiceException extends Exception {}
public static void saveAccounts(List<Account> accounts) {
try {
insert accounts;
} catch (DmlException e) {
throw new AccountServiceException(
'Could not save accounts: ' + e.getDmlMessage(0)
);
}
}
}Exercise
A list holds three accounts. The first and third are valid, and the second is missing a required field. You run insert accounts; inside a try block that catches DmlException. How many of the three accounts are saved, and which method gives you the position of the failed record?
Show answer
None of the three are saved, because a DML statement rolls back the whole operation when any record fails. getDmlIndex(i) returns the position of the failed record in the input list.