Error Handling in Salesforce Apex

Error Handling in Salesforce Apex

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 

Error Handling in Salesforce Apex

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).

Error Handling in Salesforce Apex

b. QueryException:

Occurs during SOQL query failures (e.g., no records found, too many rows).

Error Handling in Salesforce Apex

c. NullPointerException

Thrown when accessing a null object reference.

Error Handling in Salesforce Apex

d. ListException

Occurs with invalid list operations (e.g., accessing an out-of-bounds index).

Error Handling in Salesforce Apex

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

To create your custom exception class, extend the built-in Exception class and make sure your class name ends with the word Exception. Append extends Exception after your class declaration as follows.

Step 2: Use the Custom Exception in Your Code

 

 

5. Finally Block

The finally block executes code regardless of whether an exception is thrown. Use it for cleanup tasks like releasing resources.

Error Handling in Salesforce Apex

6. Transaction Control with Savepoints

Use Savepoint to roll back transactions if an error occurs.

7. Logging Errors

Log errors to debug logs or custom objects for auditing.

Example: Logging to a Custom Object

Also Read – Salesforce Flow Best Practices

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

  1. Use Specific Exceptions: Catch specific exceptions (e.g., DmlException) instead of a generic Exception.
  2. Avoid Empty Catch Blocks: Never leave a catch block empty—log or handle the error.
  3. Limit Try Block Size: Only wrap code that might throw an error in try.
  4. Test Error Scenarios: Write unit tests to cover exceptions (use Test.startTest() and Test.stopTest()).
  5. 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.

Conclusion

Mastering error handling in Apex ensures your Salesforce applications are resilient, user-friendly, and maintain data integrity. By leveraging try-catch blocks, built-in exceptions, custom validations, and transaction control, you can build robust solutions that handle failures gracefully. Start implementing these techniques in your code today to reduce debugging time and enhance user trust!

Get a complete Roadmap To Learn Salesforce Admin And Development

Share Now

Satyam Parasa is a Salesforce and Mobile application developer. Passionate about learning new technologies, he is the founder of FlutterAnt.com, where he shares his knowledge and insights.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *