In Salesforce Apex, whenever we want to handle an error or event that interrupts the flow of code execution and disturbs the application’s normal flow, we can use exception handling to keep the application running normally.
In this Salesforce Apex tutorial, we will learn about exception handling in Salesforce Apex. I have explained what exceptions are, the difference between errors and exceptions, try, catch, and, finally, block in Apex.
What is Exception Handling 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.
Let’s understand this with an example: the DML statements return run-time exceptions or errors if anything goes wrong in the database during the execution of the DML operation. This interrupts the flow of code, and execution is terminated.
Now, using exception handling, we can manage the exception by embedding the DML code in a try block, which we want to execute. We can handle errors in the catch block to run this execution smoothly.
Difference Between Error and Exception in Apex
The error and exception are not the same. Let’s understand these concepts. An error occurs whenever you create a code and try to save that particular code. At that time, anything restricts you from saving the code, like a syntax error or any variable-defined error, which we can call an error or compile-time error. We can resolve these errors at compile time, which means we can resolve that error immediately and save the code.
Now, the exception is the run-time error, which means that after creating any code, it will get saved without any compile-time error, and the code will look fine without any error. However, the code depends upon other things that will identify whether this will work fine during execution. If anything gets wrong during execution, it will stop the particular program or code.
Explain Try, Catch, and Finally Block in Exception Handling
Below, I have explained in detail the blocks that we used to handle exceptions in Salesforce Apex.
Try block in Apex:
In Salesforce Apex, a try block is part of exception handling. It handles errors and prevents them from interrupting the normal flow of execution. The try block allows us to write code that may throw an exception and handle that exception if it occurs.
Catch block in Apex:
The catch block is used in exception handling. It allows us to define how to handle specific types of exceptions that might occur in the try block. When an exception occurs, Apex jumps from the try block directly to the catch block to handle the error instead of interrupting code execution with an unhandled exception. If the try block does not throw an exception, then the catch block is skipped.
Finally block in Apex:
In Salesforce Apex, the finally block is optional in exception handling. It contains code that will always execute, regardless of whether an exception occurs in the try block or is caught in the catch block.
Syntax of Exception Handling in Apex
try {
// enter logic which might throw exception;
}
catch {
// handle exception;
}
finally {
// any message or operation;
}Example: Exception Handling in Salesforce Apex
For example, you want to create an account record using Salesforce Apex and get an error while creating the record. If any error or exception occurs, we need to handle that exception without interrupting the code execution flow.
In the below Apex class, I created a method in which I developed logic for creating account records. Then, in the try block, I entered logic for creating account records, and we used to enter logic in the try block when it might throw an exception during the execution of the code.
Any exception thrown by the try block should be caught, and the catch block will catch it. For that, we declared the catch block and passed the parameter, which is the generic Exception, and it accepts all types of exceptions irrespective of whatever exception will be thrown from the try block.
Then, the finally block will be executed, whether the try-and-catch block is executed or not. The finally block always gets executed. Save and execute this Apex code.
public class ExceptionHandling {
public void CreateAcc() {
try {
List<Account> Alist = new List<Account>();
Account acc = new Account();
acc.Name = 'TSinfo Technologies';
acc.Rating = 'Hot';
Alist.add(acc);
Insert Alist;
System.debug ('Account Record Created Successfully.');
}
catch (Exception e) {
System.debug ('Error: ' + e.getMessage());
}
finally {
System.debug ('Execution completed.');
}
}
}Now, I leave the account name null and execute the code to create the record. As the code executes, I try to block the exception, catch the block, handle the exception, and display the error. After that, without any interruption, the finally block also gets executed. That means the flow of execution has not failed.

Now, I entered the account name and again executed the code. This time, you can see the try block executed and the record created without any exception. Because no exception was thrown, the catch block is not executed; instead, directly, the finally block gets executed.

In this way, we can handle the exception using a try-catch block in Salesforce Apex.
Exception Class Methods in Salesforce Apex
The exception class methods are very helpful in detecting and managing errors efficiently. These methods are available in the Exception class and its subclasses, such as DmlException, NullPointerException, etc.
Below, I have explained some exception methods that are often used in exception handling and how to use them in the Apex class to handle exceptions in Salesforce.
1. getMessage() Method in Exception Handling
In Apex, the getMessage() method handles exceptions and retrieves the error message associated with them. When an exception occurs, it generates a message describing the issue, which can be accessed using this method.
2. getLineNumber() Method in Exception Handling
The getLineNumber() is an Exception class method in Apex that returns the line number in the code where the exception is thrown.
3. getTypeName()
In Apex, the getTypeName() method is used within exception handling to retrieve the type or class name of the exception that has been thrown.
4. getCause()
The getCause() method in Apex exception handling is used to retrieve the basic reason for an exception if it exists. Specifically, it returns the exception that occurred because of any other exception, allowing us to understand the original issue when an exception is thrown due to a lower-level issue.
I have explained the exception class methods we saw above in the Apex code below. Let’s examine how to use these methods in Apex code.
In the below class, I’m creating an account record in the try block. If an exception occurs, it will be handled in the catch block, which will display the error messages. Here, I displayed error information using the exception class methods.
After that, save the code and execute it by creating a class instance and calling the method.
public class EceptionHandling {
public void CreateAcc() {
try {
List<Account> Alist = new List<Account>();
Account acc = new Account();
acc.Name = null;
acc.Rating = 'Hot';
Alist.add (acc);
Insert Alist;
System.debug ( 'Account Record Created Successfully.' );
}
catch (DmlException e) {
System.debug (' Error message: ' + e.getMessage());
System.debug (' Error line: ' + e.getLineNumber());
System.debug (' Error type: ' + e.getTypeName());
System.debug (' Error Reason: ' + e.getCause());
}
finally {
System.debug ( 'Execution completed.' );
}
}
}After executing the above code in the output, you can see that the method we displayed in the catch block is displayed along with the details of errors that occurred in the try block.

In this way, we can use exception class methods to display the details of errors in exception handling in Salesforce Apex.
Throw Statement in Apex Exception Handling
In Apex, the throw keyword is used to create and signal an error on purpose when something goes wrong in the code. When a throw is used, the current method stops running and looks for a catch block to handle the error. If a catch block is found, it takes over and handles the exception. If there is no catch block, the error continues to move up to other methods.
Syntax:
Here, you need to declare throw and new keyword, then ExceptionType, such as CustomException, NullPointerException, DmlException, etc. In the parenthesis, you can enter a message that you want to display.
throw new ExceptionType ( 'Custom exception message' );In the Apex code below, I have used the throw statement to display an error message when something goes wrong.
Let’s take an example. We want to validate alphabetical fields while the user enters the details. We can check if the user enters any character except the alphabet.
As we are using the throw statement to signal an exception with ExceptionType as customException, we need to declare the class that extends the exception class.
In the Apex class below, I added the method with an account as a parameter. In the if condition, we check whether any account name contains a character or symbol other than letters. If another character is found, it will throw an exception, and the record will not be saved.
public class StringMethod {
public class CustomException extends Exception {}
public void CheckStringMethod (Account acc) {
if (String.isEmpty (acc.Name) || !acc.Name.isAlpha()) {
throw new CustomException (' Name must contain only alphabetic characters.');
}
try {
upsert acc;
System.debug (' Employee record saved successfully.');
}
catch (Exception e) {
System.debug (' Error saving employee record: ' + e.getMessage());
}
}
}As we execute the above code, I first enter the account name, which contains only the alphabet. Then, in the output, you can see the record is successfully saved.

Now, we will see if we added a number to the account name and what will happen. As I executed the code, the record was not saved because we threw an exception if the account name contained any character except the alphabet.

In this way, we can use a throw statement to display an error if anything goes wrong in the Apex code to handle the exception.
I have also created a complete video on exception handling. Have a look at it.
Conclusion
I hope you have an idea about exception handling in Salesforce Apex. In this tutorial, I have explained the difference between exceptions and errors. Then, we saw what try, catch, and finally blocks in Apex, along with syntax and examples to handle the exception thrown by the try block.
After that, I explained some exception class methods that display details of errors we got in the catch block. Then, we saw what the throw keyword is and used it to signal an error if anything went wrong in the try block.
You may like to read:
- Apex String Methods to Determine Character Types in Salesforce
- Send An Email to User and Public Group Using Apex in Salesforce
- Define and Use Constants in Salesforce Apex Classes
- Create and Use Constructors in Salesforce Apex Classes
- Write a Test Class For an Apex Trigger in Salesforce
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.