We have seen Exception Handling in Salesforce Apex, which is used to handle an error or event that interrupts the flow of code execution and disturbs the application’s normal flow. To handle exceptions, there are two types of exceptions. Using them, we can display common issues.
In this Salesforce tutorial, we will learn about different types of exceptions in Salesforce Apex. I will explain how to use different types of exceptions in Apex code and their role in handling errors in Salesforce Apex.
Types of Exceptions in Salesforce Apex
In Salesforce Apex, exception handling is very important for handling unexpected errors in the code execution flow. It allows us to handle errors and take appropriate actions or log errors for debugging purposes.
There are two types of exceptions in Salesforce Apex:
- System Exception.
- Custom Exception.
System Exception in Salesforce Apex
In Salesforce Apex, system exceptions occur when the Apex runtime engine throws an error. These errors are usually due to attempts to perform invalid operations. Unlike other exceptions arising from user code or logic issues, system exceptions are usually out of the developer’s control and require handling to prevent unexpected behavior or application failure.
Types of System Exception in Salesforce Apex
A system exception is a type of Exception, and different subtypes of system exceptions are used to handle exceptions. Below, I have explained some subtypes of system exceptions.
1. DmlException
DmlException in Salesforce Apex is a specific type of exception that occurs when there is an issue performing Data Manipulation Language (DML) operations. DML operations include actions like insert, update, delete, and undelete on Salesforce records. When a DML operation fails, an instance of DmlException is thrown, which can be caught and handled in Apex code to manage the error effectively.
Example: Use DmlException in Apex Exception Handling
Let’s take an example: We want to create a new contact record, and for that, we will use a try-catch block so that if any exception interrupts the normal flow of code, we can handle it.
I entered the logic to create a contact record in the try block so that if any exception occurs, it can be handled in the catch block. As we know, when we create or manipulate data in the Salesforce database, the DML operation happens, and for that, we can use DmlException as a system exception to handle the error.
So in the catch block, we declared DmlException, and using the getMessage method, we displayed the error whatever will get. Save the below Apex code and execute it.
public class EceptionHandling {
public void CreateCon() {
try {
Contact con = new Contact();
con.FirstName = 'Alex';
insert con;
}
catch ( DmlException e ) {
System.debug( ' The DML Exception is : ' + e.getMessage() );
}
}
}As you execute the code, you will get a DmlException because the record will not get saved in the database. The reason is that we missed adding one required field value.

So in this way, we can use DmlException to handle the error while inserting, updating, or deleting records from the Salesforce database.
2. QueryException
A QueryException in Salesforce Apex occurs when an issue executes a SOQL (Salesforce Object Query Language) or SOSL (Salesforce Object Search Language) query. This exception indicates a problem with the query’s structure, logic, or constraints.
Example: Use QueryException in Apex Exception Handling
Here, I explained the example of fetching the record from Sobject. To fetch the record from the Salesforce database, we need to enter a query. Whenever there is a query, we can use QueryException to handle the exception and display the appropriate message about the exception occurring.
public class EceptionHandling {
public void FetchAcc() {
try {
Account acc = [ SELECT Id, Name FROM Account WHERE Name = 'Jhony' ];
}
catch (QueryException e) {
System.debug(' Query Exception: ' + e.getMessage() );
}
}
}As I execute the above Apex code, you can see the error message we got because of the account name we entered; there is no such type of account in the Salesforce database, and that is why this QueryException occurs.

In this way, we can use the QueryException to avoid or handle the issue that executes a SOQL or SOSL query in Salesforce Apex.
3. NullPointerException
In Salesforce Apex, a NullPointerException is a runtime exception that occurs when you try to access or manipulate an object, variable, or field that has no value assigned to it. This type of exception is common in many programming languages, and it typically happens in Apex when you try to perform actions on a null reference.
Example: Use NullPointerException in Apex Exception Handling
In the Apex code below, I declared an integer a and didn’t assign a value, so it is a null variable. Then, in the try block, we multiplied the null value by an integer, which will lead to a null pointer exception.
In the catch block, we declared NullPointerException because we performed an operation on the null variable. The catch block handled the exception to keep the execution flow continuing.
public class Demo {
public void myMethod() {
try{
system.debug ('Program Started');
Integer a;
Integer b = a * 10;
system.debug ('Multiplication is : '+b);
}
catch (NullPointerException e) {
system.debug ('The Error is ' + e.getMessage());
}
system.debug ('Program Ended');
}
} As we execute the code, you can see that it starts to execute in the catch block. It handled the exception and displayed the appropriate error message, and without stopping the code, the next line of code is also executed.

In this way, we can use NullPointerException to handle the null value exception and continue the flow of exceptions.
4. StringException
A StringException in Salesforce Apex is an exception type that occurs when invalid operations are performed on strings. This exception is raised when you attempt to perform an action that breaks the rules of string manipulation or when improper usage of string methods occurs.
StringException can be raised by various methods in the String class, such as accessing a character at an invalid index, splitting a string with an invalid limit, or calling a method with wrong arguments.
Example: Use StringException in Apex Exception Handling
In this example, I declared one string variable, and in the try block, I’m trying to display the character at the 10th position in this string. However, this string doesn’t have a very long length, so it will definitely throw an exception. Because charAt() is a string method, we can use StringException to handle the error.
public class EceptionHandling {
public void HandledException() {
String str = 'Hello';
try {
System.debug ( str.charAt(10) );
}
catch (StringException e) {
System.debug(' String Exception caught: ' + e.getMessage() );
}
}
}As we execute the above code, you can see that in the catch block, we declared the StringException with the getMessage() method, which will display the actual error message.
In the output, we got a message about why this exception occurred.

In this way, we can use StringException to handle the exception of string-related errors and keep the normal flow of code execution.
5. ListException
In Salesforce Apex, a ListException occurs when working with lists (or arrays). Lists are collections of elements that can store multiple values of the same data type, and they’re widely used in Apex for handling multiple records, such as a list of Account or Contact objects.
This exception occurs when you attempt to access a list element by an index that does not exist in the list, and Apex list indices are zero-based, which means the first element is at index 0.
Example: Use ListException in Apex Exception Handling
Let’s take an example: You fetched a record from an account and stored it in the list, and you want to display a particular account record to see the record details. For that, I created an Apex class and method.
In the try block, I created a List to store account records whose rating is cold and displayed those records. After that, I declared a Sobject variable to store the particular record details, and using the list name, I fetched the 100th record from the list of account records.
As we are fetching a list record, if there is an exception in the try block, we need to declare ListException in the catch block to handle the exception and continue the code’s execution. Using the getMessage() method, we display the error message.
public class EceptionHandling {
public void HandledException() {
try {
List<Account> accounts = [SELECT Id, Name, Rating FROM Account Where Rating = 'Cold'];
for (Account acc : accounts) {
System.debug ('Account Name: ' + acc.Name + ', Account ID: ' + acc.Id + ', Rating: '+ acc.Rating);
}
Account record = accounts [100];
System.debug (' 100th number record is : '+record);
}
catch(ListException e) {
system.debug (' The Exception is : ' +e.getMessage());
}
Finally {
System.debug ('**** Flow of Execution Continued ****');
}
}
}As I execute the above Apex code, you can see in the output that we don’t have 100 records in the list from which we fetched cold rating accounts records. That’s why we can see an error in the exception message. After the try-catch block, the finally block is also executed.

In this way, we can use the ListException to handle the list exception in Salesforce Apex.
Custom Exception in Salesforce Apex
A custom exception in Apex is a user-defined class that extends the Exception class. Salesforce provides a standard Exception class for error handling; however, generic exceptions often don’t provide sufficient information about an error. Custom exceptions allow for the definition of more descriptive error messages that can be managed accurately.
Example: Use Custom Exception in Apex Exception Handling
In the example below, I tried to create a new account record. While creating the records, I wanted to ensure that the account name contained only alphabetic characters. If any other character is present, I throw a custom exception for the alphabetic character.
To add the custom exception, we need to declare a class that extends the Exception class. I then added an error message in the created class using the throw keyword.
public class EceptionHandling {
public class CharacterException extends Exception {}
public void HandledException (Account acc) {
try {
if ( String.isEmpty (acc.Name) || !acc.Name.isAlpha() ) {
throw new CharacterException('Name must contain only alphabetic characters.');
}
upsert acc;
System.debug (' Employee record saved successfully.');
}
catch (DmlException e) {
System.debug (' Error saving employee record : ' + e.getMessage() );
}
catch (CharacterException e1) {
System.debug (' The Custom Exception is : ' + e1.getMessage() );
}
}
}To execute the above Apex code, we need to create an Account object instance and then, using that instance, create an account record. Here, I entered the account name in alphanumeric format, so I will get an exception.
Account a = new Account();
a.Name = 'TSinfo 123';
EceptionHandling e = new EceptionHandling();
e.HandledException(a);After the code is executed, the first catch block is not executed because it is not a DML exception; instead, the custom exception message is displayed.

In this way, we can create user-defined exceptions to define more descriptive error messages that can be managed accurately in Salesforce Apex.
Conclusion
I hope you have an idea about the different types of exceptions in Salesforce Apex. In that, I have explained system exceptions and their subtypes, which are used to handle different types of exceptions. Then, we saw custom exceptions and learned how to use these exceptions in Salesforce Apex to handle errors and continue normal flow execution.
You may like to read:
- Exception Handling in Salesforce Apex
- Asynchronous Apex in Salesforce
- Salesforce Object Query Language (SOQL) in Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.