Error Handling in Salesforce Apex is a critical aspect of building robust and reliable applications in Salesforce Apex. Proper error handling ensures that your code gracefully manages unexpected scenarios, maintains data integrity, and provides meaningful feedback to users.
In this guide, we’ll explore the fundamentals of error handling in Apex, including built-in exceptions, custom exceptions, transaction control, and best practices all illustrated with practical examples.
1. Why Error Handling Matters in Apex
- Prevent Crashes: Handle exceptions to avoid unhandled errors that disrupt user workflows.
- Data Integrity: Use transactions to roll back changes if an error occurs, ensuring consistent data.
- User Experience: Display clear error messages instead of cryptic system-generated alerts.
- Debugging: Capture error details for troubleshooting and auditing.
2. Basic Try-Catch Block
The try-catch block is the foundation of error handling in Apex. Code that might throw an error is placed in the try block, and exceptions are caught and handled in the catch block.
Example: Handling a DML Exception
Explanation:
- The insert operation fails because LastName is required for a Contact.
- The catch block catches the DmlException and logs details like the error message and affected fields.
3. Built-in Exceptions in Apex
Apex provides several standard exceptions. Here are the most common ones:
a. DmlException:
A DmlException is thrown when there is an issue with a DML operation (insert, update, delete, undelete).
b. QueryException:
Occurs during SOQL query failures (e.g., no records found, too many rows).
c. NullPointerException
Thrown when accessing a null object reference.
d. ListException
Occurs with invalid list operations (e.g., accessing an out-of-bounds index).
4. Custom Exceptions
In Apex, you can define a custom exception class by extending the built-in Exception class. Custom exceptions are useful when you want to handle specific error conditions in your code.
Here’s a simple example of how to define and use a custom exception class in Apex:
Step 1: Define the Custom Exception Class
5. Finally Block
The finally block executes code regardless of whether an exception is thrown. Use it for cleanup tasks like releasing resources.
8. Handling errors in Lightning Web Components (LWC)
Handling errors and exceptions in Lightning Web Components (LWC) is crucial for building robust and user-friendly applications. In LWC, you can handle errors and exceptions in several ways, such as using try-catch blocks, leveraging the lightning/uiRecordApi error handling, or displaying error messages to users.
Here are some examples of how to handle errors and exceptions in LWC:
1. Using try-catch Blocks
You can use try-catch blocks to handle errors in JavaScript code.
In this example:
- The try block contains code that might throw an error.
- The catch block catches the error and logs it to the console.
- A toast message is displayed to the user using the lightning/platformShowToastEvent module
2. Handling Errors in lightning/uiRecordApi
When working with Salesforce data using lightning/uiRecordApi, you can handle errors using the error property returned by the API.
In this example:
- The @wire decorator is used to fetch a record.
- If an error occurs, it is logged to the console, and a toast message is displayed to the user.
3. Handling Apex Method Errors
When calling Apex methods from LWC, you can handle errors in the error callback.
In this example:
- The Apex method getAccountData is called.
- If the method fails, the error is caught in the catch block, and a toast message is displayed.
9. Best Practices
- Use Specific Exceptions: Catch specific exceptions (e.g., DmlException) instead of a generic Exception.
- Avoid Empty Catch Blocks: Never leave a catch block empty—log or handle the error.
- Limit Try Block Size: Only wrap code that might throw an error in try.
- Test Error Scenarios: Write unit tests to cover exceptions (use Test.startTest() and Test.stopTest()).
- Use addError() in Triggers: Display user-friendly errors in record operations.
FAQs
1. How to display an error message in Apex?
In Apex, you can display an error message to users using the following methods:
- ApexPages.addMessage – Displays an error message on a Visualforce page.
- addError() – Stops record DML execution and shows an error in the UI.
- Messaging.sendEmail() – Sends an email notification to inform users about an error.
2. What is the ‘Apex CPU Time Limit Exceeded’ error in Salesforce?
The Apex CPU Time Limit Exceeded error in Salesforce occurs when an Apex transaction surpasses the CPU time restriction set by Salesforce governor limits. For synchronous transactions, Salesforce allows a maximum CPU time of 10 seconds per transaction, while asynchronous processes have a higher limit of 60 seconds.