Sub topic 3
Catching DmlException when a statement fails
This chapter assumes you can write Apex classes and methods, use try/catch, and work with lists of SObjects. It also assumes you know that Apex runs in a transaction under governor limits. The previous chapter showed the DML statement syntax (insert, update, upsert, delete, undelete). This chapter covers what happens when one of those statements fails.
What a failing statement does
A DML statement is all-or-nothing. If any record in the statement fails, the statement throws a System.DmlException. The statement saves none of its records, even the valid ones. The failure can come from a missing required field, a validation rule, a duplicate rule, a trigger that calls addError(), a sharing or field-level restriction, or a value that does not fit its field.
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());
}After the catch block runs, no Account from the list exists in the database. The valid Acme record was rolled back with the invalid one.
The diagram shows the flow.
Reading the exception
DmlException.getMessage() returns a single string. It is fine for logs, but it is not enough when you need to know which records failed. DmlException has indexed methods for that. Each takes an index from 0 to getNumDml() - 1. That index counts the failures. It does not count the records in your input list.
| Method | Returns |
|---|---|
| `getNumDml()` | The number of failed records |
| `getDmlIndex(i)` | The position, in the original input list, of the i-th failed record |
| `getDmlMessage(i)` | The error message for the i-th failure |
| `getDmlStatusCode(i)` | The status code as a string, such as `REQUIRED_FIELD_MISSING` |
| `getDmlType(i)` | The same status code as a `System.StatusCode` enum value |
| `getDmlFieldNames(i)` | The names of the fields involved, as a `List<String>` |
| `getDmlFields(i)` | The same fields as `Schema.SObjectField` tokens |
| `getDmlId(i)` | The ID of the failed record, which is `null` for failed inserts |
This example loops over the failures and maps each one back to its input record:
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account(),
new Account(Name = 'Globex'),
new Account()
};
try {
insert accounts;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
Integer inputPosition = e.getDmlIndex(i);
System.debug(
'Input record ' + inputPosition + ' failed: ' +
e.getDmlStatusCode(i) + ' - ' + e.getDmlMessage(i) +
' Fields: ' + e.getDmlFieldNames(i)
);
}
}The loop variable i is the failure number. e.getDmlIndex(i) gives the position in accounts. If you index accounts with i directly, you point at the wrong record.
On a failed insert, the statement has not created the record, so getDmlId(i) returns null. It returns a useful ID for update and delete failures.
How many failures does the exception report?
getNumDml() is the number of records the platform reported as failed. It is not always the number of records that went unsaved. The platform can report only the records that caused a failure. Valid records are rolled back without an error entry.
In the example above, the two valid accounts are not saved, but only the two invalid ones appear in getNumDml(). Do not treat the failure list as the list of unsaved records. After a caught DmlException from a statement, assume none of the input records were saved.
Where the exception comes from
You usually do not see the failure's root cause in your own code. Many DmlException instances originate somewhere else:
- Validation rules and required fields. The status code is
FIELD_CUSTOM_VALIDATION_EXCEPTIONfor a validation rule andREQUIRED_FIELD_MISSINGfor a missing required field. - Triggers. A trigger that calls
record.addError('message')causes aDmlExceptionin the code that ran the DML. The message you wrote appears ingetDmlMessage(i). The status code isFIELD_CUSTOM_VALIDATION_EXCEPTIONfor both validation rules andaddError(), so do not use it to tell them apart. - Mixed DML. Changing a setup object such as
Userand a non-setup object such asAccountin the same transaction throws aDmlExceptionwith the codeMIXED_DML_OPERATION. - Field limits and format. Text that is too long gives
STRING_TOO_LONG. A bad ID or picklist value gives errors such asINVALID_CROSS_REFERENCE_KEYorINVALID_OR_NULL_FOR_RESTRICTED_PICKLIST. - Locking.
UNABLE_TO_LOCK_ROWappears when another transaction holds a lock on a record you are updating.
You can branch on the status code instead of parsing message text. Message text can change, and the status code does not.
try {
update contacts;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
if (e.getDmlType(i) == StatusCode.UNABLE_TO_LOCK_ROW) {
System.debug('Lock contention on ' + e.getDmlId(i) + ', consider retrying');
} else {
System.debug('Unexpected failure: ' + e.getDmlMessage(i));
}
}
}What a catch block does not undo
When you catch the exception, Apex rolls back only the failed statement. Earlier DML in the same transaction stays in place, and the transaction continues. Most surprises about DmlException come from this behavior.
insert new Account(Name = 'Saved first');
try {
insert new Contact(); // LastName is required, so this fails
} catch (DmlException e) {
System.debug('Contact failed: ' + e.getMessage());
}
// 'Saved first' is still part of the transaction and will commit
// when the transaction finishes successfully.The Account insert is not undone by the catch. If the rest of the transaction succeeds, the Account commits. If you want a failure to undo earlier work, you have two options:
- Let the exception propagate. An uncaught exception rolls back the whole transaction.
- Use a savepoint and call
Database.rollback(). A later chapter covers this.
Catching the exception also removes the signal that something went wrong. Code that catches a DmlException, logs it, and returns normally tells the caller that everything worked. If the caller must know about the failure, rethrow the exception or return an explicit result.
Common mistakes
- Catching
Exceptiontoo early. A broadcatch (Exception e)also catches other errors, such as aNullPointerExceptionfrom a bug in your code. CatchDmlExceptionfirst, and add a generic handler only where you need it. - Trying to catch a limit error. A
System.LimitException, such as too many DML statements, cannot be caught. Yourcatch (DmlException e)block does not run for it, and the transaction ends. Limit errors are covered in a later chapter. - Using the wrong index.
getDmlIndex(i)maps a failure back to your input list. The loop counter does not. - Swallowing the error. An empty
catchblock hides failures. Log them, rethrow them, or return them to the caller. - Assuming the valid records saved. With a DML statement, one bad record prevents the whole statement from saving. If you need the valid records to save, the Database methods with
allOrNoneset tofalseare the tool for that. The chapter onallOrNonecovers them. - Showing raw messages to users.
getMessage()can include record IDs and internal detail. In a UI-facing method, convert it to a message you control. For example, throw anAuraHandledExceptionwith a safe message.
Rethrowing with context
A common pattern is to catch the exception, add information, and throw a custom exception that your callers know how to handle:
public class AccountService {
public class AccountSaveException extends Exception {}
public static void createAccounts(List<Account> accounts) {
try {
insert accounts;
} catch (DmlException e) {
List<String> problems = new List<String>();
for (Integer i = 0; i < e.getNumDml(); i++) {
problems.add(
'Row ' + e.getDmlIndex(i) + ': ' + e.getDmlMessage(i)
);
}
throw new AccountSaveException(
'Could not save accounts. ' + String.join(problems, '; ')
);
}
}
}This keeps the failure visible and tells the caller which input rows were the cause. Because the exception is thrown out of the method, the caller decides whether to roll back or continue.
Summary
A DML statement throws DmlException when any record fails, and it saves none of its records. The exception exposes per-failure detail through getNumDml() and the indexed methods, and getDmlIndex(i) links each failure to the input list. Catching the exception rolls back only the failed statement, so earlier DML in the transaction remains. The Database class methods report errors differently, and the next chapters cover them.
Exercise
A list of five Contacts is inserted with insert contacts; inside a try/catch for DmlException. Contacts at positions 1 and 3 have no LastName. In the catch block, e.getNumDml() returns 2. Which method do you call to find that the second failure belongs to the contact at position 3 in contacts, and how many of the five contacts are saved?
Show answer
Call e.getDmlIndex(1), which returns 3 (the second failure, loop index 1, maps to input position 3). None of the five contacts are saved, because a DML statement rolls back all of its records when any one fails, including the three valid ones.
Exercise
A method inserts an Account, then runs try { insert new Contact(); } catch (DmlException e) { System.debug(e.getMessage()); }, and then returns normally. The Contact has no LastName. Is the Account saved, and why?
Show answer
Yes. The catch block handles the failed Contact statement, and only that statement is rolled back. The Account insert completed earlier, and the transaction ends normally, so it commits. To undo the Account, rethrow the exception or use a savepoint with Database.rollback().