Is it possible to throw an exception while performing a DML on a list of records, such that, successful records are committed to DB, but exception is thrown for the records which failed?
If I use Database class for DMLs with the allOrNone parameter set to false, successful records are getting commited, but no exceptions are thrown.

2 Answers 2


You could do something like this :

for (Database.SaveResult sr :  this.someRecords) {
    if (sr.isSuccess()) {
        // Operation was successful
    else {
        // Operation failed
        for(Database.Error err : sr.getErrors()) {
            throw new CustomExceptionClass(err.getMessage());
  • In this case, won't the successful DMLs be rolled back? May 13, 2017 at 8:26
  • Depends on which parameters you provide with Database.insert(), so yes. You could also have a boolean set up to check if even one record failed to save and then throw an exception
    – d_k
    May 13, 2017 at 8:40
  • 1
    @d_k - throwing the error throws the error for the class no the individual record. Doing this will cause all records in scope to fail
    – Eric
    May 14, 2017 at 1:34

The system automatically rolls back a transaction if any exception makes it all the way up to the top of the call stack. You can't currently have any DML modifications survive an uncaught exception. I created this idea as something I believe would be practical: the ability to do something in response to a failed transaction asynchronously when an exception is thrown (e.g. in your case, we could take the survivors, stuff them into an asynchronous transaction, then throw an exception).

  • 1
    As a workaround to log failures, I am iterating over the list of SaveResults, and for unsuccessful ones, instead of throwing an Exception, I am creating a new CustomException with the error details as the message, and sending that exception to my Exception Logging Utility class which saves the exception details in a Custom Object. I am yet to test this, but it should work. May 14, 2017 at 13:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .