DML Operations and Exception Handling in Apex

May 09, 2025
493 Views
DML Operations and Exception Handling in Apex

Welcome to day 6 of the 10 day Apex series. Working with data is essential and required for any Salesforce Developer. Learning how to insert, update, delete, undelete and merge records and how to handle errors that might come up during these operations to understand it is very helpful.

In this blog, we will learn about DML (Data Manipulation Language) operations in Apex and share some simple examples along with tips for handling and managing exceptions.

DML Operations

DML operations in Apex allow us to interact with Salesforce records. Whether we are inserting data or updating existing data, these operations are the main blocks for maintaining records. We will now understand the basic DML actions.

Inserting Records

Creating new records is the first DML operation we will perform and which is common. With Apex, inserting a record is easy.

public class SimpleDML {
    public static void insertAccount() {
        // Create a new Account record and set its name
        Account newAccount = new Account(Name = 'Acme Corporation');
        
        // Insert the record into Salesforce
        insert newAccount;
        
        // Log the record ID for confirmation
        System.debug('Inserted Account with Id: ' + newAccount.Id);
    }
}
Inserting Records
Inserting Records 2
In this example, we:
  • Create an Account
  • Set its Name
  • Use the insert command to add the record.

Log the inserted record’s Id for reference.

Updating Records

We will now learn about updating records which is as simple as inserting them. We simply update the fields of a record and apply the update.

public class SimpleDML {
    public static void updateAccount() {
        // Retrieve an existing Account record by ID
        Account acc = [SELECT Id, Name FROM Account WHERE Id = '001dM00002SEQ4jQAH'];
        
        // Change the Account name
        acc.Name = 'Updated Acme Corporation';
        
        // Update the record in Salesforce
        update acc;
        
        // Log the updated name for confirmation
        System.debug('Updated Account Name to: ' + acc.Name);
    }
}

The provided account record is updated with a new name using the update command.

Updating Records
Deleting Records

Deleting records removes them from the database and our org. It is important to use the delete operation properly to avoid data loss.

public class SimpleDML {
    public static void deleteAccount() {
        // Retrieve the Account record to be deleted by ID
        Account acc = [SELECT Id, Name FROM Account WHERE Id = '001dM00002SEQ4jQAH'];
        
        // Delete the specified Account record
        delete acc;
        
        // Log confirmation of deletion
        System.debug('Deleted Account with Id: ' + acc.Id);
    }
}

The above code shows the delete operation, which permanently removes the record (unless it is later undeleted).

Undeleting Records

If we got to know that the record was mistakenly deleted, Salesforce gives us a chance to bring it back using the undelete operation.

public class SimpleDML {
    public static void undeleteAccount(List<Account> accountsToRestore) {
        // Undelete the provided Account records
        undelete accountsToRestore;
        
        System.debug('Undeleted Accounts');
    }
}

The above example shows how to undelete a list of accounts using the undelete command.

Advanced DML Operations: Upsert and Merge

Sometimes we do not know whether a record already exists or not. Instead of writing separate logic to insert or update, we can use the upsert operation which will provide in-built to check which operation to perform insert or update.

Upsert Operation

Upsert is a combination of insert and update. It checks whether a record exists (usually based on an external or Salesforce ID) and performs an insert if it is not present or an update if it already exists in the system.

public class SimpleDML {
    public static void upsertAccount(Account acc) {
        // Upsert the Account record. If it exists, update it; if not, insert a new record.
        upsert acc;
        
        System.debug('Upserted Account with Id: ' + acc.Id);
    }
}

In the above example, upsert command handles both creating and updating records based on whether the record’s identifier is present or not.

Merge Operation

When we have duplicate records and want to combine them into one, the merge operation comes into play. Merge operation is very useful when cleaning up data by combining duplicate records and keeping correct records in the system.

public class SimpleDML {
    public static void mergeAccounts(Account masterAccount, Account duplicateAccount) {
        // Merge duplicateAccount into masterAccount
        merge masterAccount duplicateAccount;
        
        System.debug('Merged duplicate account into master account: ' + masterAccount.Id);
    }
}

In this code/example, two account records are merged, with the duplicate being combined into the master record. Note that merge operations work only on records of the same object type.

Handling Exceptions in DML Operations

When we are working with DML, processes or operations might not go as planned sometimes. For example, we might try to update a record with invalid data. Handling exceptions effectively will help us code fail neatly.

Using Try-Catch for DML

A most common and useful method for managing errors in Apex is the try-catch block. It will allow us to “catch” exceptions and handle them properly rather than letting our application crash.

public class DMLExceptionHandler {
    public static void safeInsert(Account acc) {
        try {
            // Attempt to insert the account record
            insert acc;
            System.debug('Account inserted successfully.');
        } catch (DmlException e) {
            // Log the error message
            System.debug('Error inserting account: ' + e.getMessage());
        }
    }
}
In the above example:
  • The try block contains the DML operation which is insert.
  • If an error occurs (such as a validation rule failing), the exception/error is caught in the catch

The error message is logged, allowing us to diagnose the problem.

Handling Multiple DML Operations

When performing several DML operations, it’s a good idea to wrap them in only one try-catch block so that we can handle errors properly.

public class DMLExceptionHandler {
    public static void processMultipleRecords(List<Account> accounts) {
        try {
            // Insert multiple account records
            insert accounts;
            System.debug('Inserted multiple accounts successfully.');
        } catch (DmlException e) {
            // Handle errors that occurred during the insert
            System.debug('Error inserting multiple accounts: ' + e.getMessage());
        }
    }
}

By processing/inserting multiple records in one go, we can improve performance and handling exceptions ensures that a single error will not stop the entire operation.

Best Ways For DML and Exception Handling

Below are a few ways I have learned while working with Apex:

  1. Bulk Operations: Always design code to handle multiple records at once. Salesforce has strict governor limits, so writing bulk DML operations will help us to avoid hitting those limits.
  2. Check for Null Values: Before performing updates or deletes, make sure that the records are not null to prevent unnecessary exceptions.
  3. Use Context-Specific Methods: In triggers and batch operations, make sure to check on the context (such as before insert, after update, etc.) that will choose the proper DML operations.
  4. Log Meaningful Messages: When we catch exceptions in the catch block, we will need to log proper context about the error so we can pinpoint issues afterwards.
  5. Test the Code: Use test classes to try and test different scenarios, including invalid data that is negative scenario and duplicate records, to make sure our exception handling is properly working with positive scenarios as well.
Also Read

Don’t forget to checkout: Salesforce Agentforce Prompt Engineering: Masterclass Guide.

Conclusion

Understanding DML operations and how to properly handle exceptions is a critical skill for any Salesforce developer. Whether we are inserting new records, updating existing ones or merging duplicates, being comfortable with these operations and knowing how to manage errors will help us build more reliable and efficient applications.

This is Day 6 of the Apex 10-Day Series: DML Operations and Exception Handling in Apex.

On Day 7, we’ll dive into Apex Classes, Methods, and Constructors. Stay tuned and happy coding!

Written by

user

Mohit Bansal

Salesforce Technical Architect | Lead | Salesforce Lightning & Integrations Expert | Pardot | 5X Salesforce Certified | App Publisher | Blogger

Contributor of the month
contributor
Gopinath G

Passionate about the intersection of cutting-edge technologies

Get the latest tips, news, updates, advice, inspiration, and more….

...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...