Mastering Exception Handling and DML Operations in Salesforce Apex — Apex Part 6

Mohammad Usman
4 min readMar 16, 2024

--

Apex is a powerful programming language used in Salesforce development. Like any other language, Apex supports exception handling to manage errors effectively. Exception handling is crucial for writing robust and reliable code, especially when dealing with sensitive operations like Database Manipulation Language (DML) operations. In this comprehensive guide, we will delve into understanding exceptions in Apex, exploring try-catch blocks, handling different types of exceptions, and mastering DML operations.

Understanding Exceptions in Apex

What are Exceptions?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. In Apex, exceptions can occur due to various reasons such as logical errors, runtime errors, or system failures.

Types of Exceptions
Apex defines several types of exceptions, including:

1. DML Exception: Occurs when a DML operation fails, such as insert, update, delete, or undelete.
2. System Exception: These are runtime exceptions generated by the system, such as NullPointerException or LimitException.
3. Custom Exception: Developers can define custom exceptions to handle specific scenarios.

Propagation of Exceptions
When an exception occurs in Apex and is not caught by the code, it propagates up the call stack until it’s caught by an appropriate exception handler or reaches the top-level execution context.

Try-Catch Blocks in Apex

Syntax
In Apex, try-catch blocks are used to handle exceptions. The syntax is as follows:

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

Example

try {
// DML operation that might fail
insert new List<Account>(); // Example DML operation
} catch (DmlException e) {
// Handling DML exception
System.debug(‘DML Exception: ‘ + e.getMessage());
}

Best Practices
- Specific Exception Handling: Catch specific exceptions whenever possible to handle them appropriately.
- Avoid Empty Catch Blocks: Always include code to handle exceptions; empty catch blocks can lead to silent failures.
- Logging: Use system debug logs or custom logging mechanisms to log exception details for debugging purposes.

Handling Different Types of Exceptions

DML Exception Handling
DML operations in Apex are surrounded by try-catch blocks to handle DML exceptions. Common DML exceptions include:

- DmlException: Generic exception for DML operations.
- DmlInsertException: Specific to insert operations.
- DmlUpdateException: Specific to update operations.
- DmlDeleteException: Specific to delete operations.
- DmlUndeleteException: Specific to undelete operations.

Example:

try {
insert new List<Account>(); // Example DML operation
} catch (DmlException e) {
// Handling DML exception
System.debug(‘DML Exception: ‘ + e.getMessage());
}

System Exception Handling
System exceptions occur due to runtime errors or system limitations. Common system exceptions include:

- NullPointerException: Occurs when trying to access or manipulate a null object reference.
- LimitException: Occurs when Salesforce governor limits are exceeded.

Example:

try {
Integer a = null;
Integer b = 5;
Integer c = b / a; // This line will throw a NullPointerException
} catch (NullPointerException e) {
// Handling NullPointerException
System.debug(‘Null Pointer Exception: ‘ + e.getMessage());
}

Custom Exception Handling
Developers can define custom exceptions to handle specific scenarios in their applications. Custom exceptions should extend the built-in `Exception` class.

Example:

public class CustomException extends Exception {}
try {
if (someCondition) {
throw new CustomException('Custom error message');
}
} catch (CustomException e) {
// Handling custom exception
System.debug('Custom Exception: ' + e.getMessage());
}

DML Operations in Apex

Overview
DML operations are used to manipulate Salesforce records, including insert, update, delete, and undelete operations. These operations are crucial for data management in Salesforce applications.

Inserting Records

try {
insert new List<Account>(); // Example DML operation
} catch (DmlException e) {
// Handling DML exception
System.debug(‘DML Exception: ‘ + e.getMessage());
}

Updating Records

try {
update new List<Account>(); // Example DML operation
} catch (DmlException e) {
// Handling DML exception
System.debug(‘DML Exception: ‘ + e.getMessage());
}

Deleting Records

try {
delete new List<Account>(); // Example DML operation
} catch (DmlException e) {
// Handling DML exception
System.debug(‘DML Exception: ‘ + e.getMessage());
}

Undeleting Records

try {
undelete new List<Account>(); // Example DML operation
} catch (DmlException e) {
// Handling DML exception
System.debug(‘DML Exception: ‘ + e.getMessage());
}

Best Practices for DML Operations
- Bulkification: Perform DML operations on collections of records to optimize performance and avoid hitting governor limits.
- Error Handling: Surround DML operations with try-catch blocks to handle exceptions gracefully.
- Governor Limits: Be mindful of Salesforce governor limits and design your code to stay within those limits.

Resources for Further Learning

To further enhance your understanding of advanced Apex features and Salesforce development in general, here are some recommended resources:

- Salesforce Apex Developer Guide: The official Apex developer guide provides comprehensive documentation and examples for mastering Apex programming.
- Trailhead: Salesforce’s interactive learning platform offers a wide range of modules and trails on Apex development, asynchronous processing, integrations, and more.
- Salesforce Developer Blog: Stay updated with the latest news, tips, and best practices from Salesforce developers and experts through the official developer blog.
- Stack Exchange — Salesforce: Engage with the Salesforce community, ask questions, and share knowledge on Stack Exchange’s dedicated Salesforce platform.

Conclusion

Exception handling and DML operations are essential aspects of Apex development in Salesforce. By understanding different types of exceptions, implementing try-catch blocks effectively, and mastering DML operations, developers can write more robust and reliable code. Remember to follow best practices, such as specific exception handling, proper error logging, and bulkifying DML operations, to build high-quality Salesforce applications that meet business requirements while ensuring stability and performance.

--

--

Mohammad Usman

Trailblazer | Transforming Businesses through Salesforce Expertise | Salesforce Technical Architect, Consultant & Developer | Technical Lead