Apex Class

Apex Custom Exceptions

A custom exception in Apex is an exception that you define and create to handle specific error conditions or exceptional situations in your Salesforce application.

Unlike standard Apex exceptions, which are triggered on common error scenarios, custom exceptions are created when an error on your business logic occurs customizing the behavior and the error message.

Apex Custom Exceptions in Salesforce

Apex throw Custom Exception

Creating and throwing a custom exception in Apex involves defining a custom exception class and then using it to throw an exception when an exceptional condition occurs in your code.

Let's see a real scenario as example of a Custom Exception:

1. Create a Custom Exception Class in Apex

Define a new Apex class that extends the Exception class or one of its subclasses, such as AuraHandledException or VisualforceException. This new class will represent your custom exception.

public class AgeOver60Exception extends Exception {
    public AgeOver60Exception() {
        super('Account birthdate overpasses 60 years');

2. Throw the Custom Exception

In your code, identify the point where an exceptional condition occurs. This is where you'll throw your custom exception.

public class AccountUtils {
    public static void checkAccountAge(Account acc) {
        Date currentDate = Date.today();
        Integer yearsDifference = acc.Birthdate != null ? currentDate.year() - acc.Birthdate.year() : 0;
        if (yearsDifference > 60) {
            throw new AgeOver60Exception();

3. Handle the Custom Exception

In the catch block, specify how you want to handle the custom exception. You can log the error, display a user-friendly message, perform cleanup, or take any other appropriate actions. Make sure to apex catch exception to be able to display the error in the UI

try {
    Account acc = [SELECT Id, Birthdate FROM Account WHERE Id = 'YourAccountId' LIMIT 1];
    AccountUtils.checkAccountAge(acc); // THIS COULD THROW AN EXCEPTION
} catch (AgeOver60Exception ex) {
    System.debug('Age over 60 exception: ' + ex.getMessage());

Also, You can have multiple catch blocks to handle different types of exceptions. These blocks are evaluated in order, and the first matching block is executed.

try {
} catch (AgeOver60Exception ce) {
    // HANDLE AgeOver60Exception EXCEPTION
} catch (DmlException de) {
} catch (Exception e) {

4. Finish the Custom Exception (Optional)

You can optionally include a finally block after the catch blocks. Code in the finally block is executed whether an exception is thrown or not. This is useful for cleanup tasks, such as closing database connections or releasing resources.

try {
} catch (ExceptionType e) {
} finally {
    // CLEAN UP

Why you should use Custom Exceptions?

Custom exceptions matter in Apex for several important reasons, and they play a crucial role creating maintainable Salesforce applications.

  1. Enhanced Readability and Code Clarity: Custom exceptions allow you to give meaningful and descriptive names to specific error conditions in your code. This makes your code more self-documenting and easier for other developers (including your future self) to understand. Custom exceptions provide context making it clear what went wrong and why.

  2. Precise Error Identification: This precision is particularly useful when debugging or troubleshooting issues in your Salesforce application. You can quickly identify the cause of an error and take appropriate action.

  3. Code Maintainability: Custom exceptions make your codebase more maintainable in the long run. When you revisit your code or when other developers work with it, they can easily understand the error conditions and how they are handled.

  4. Consistency Across the Application: When you use custom exceptions consistently across your application, you establish a standard way to handle errors. This consistency makes your codebase more organized and predictable.

Comparison between Standard Exceptions and Custom Exceptions

Standard exceptions and custom exceptions are two types of exceptions in Apex, each serving specific purposes in error handling. Let's explore the differences between standard exceptions and custom exceptions:

1. Definition

Standard: Standard exceptions are pre-defined exceptions that are provided by the Apex language and Salesforce platform. They cover common error scenarios that can occur during code execution.

Custom: Custom exceptions are exceptions that you define and create in your Apex code to handle specific error conditions or exceptional situations that are unique to your application.

2. Examples

Standard: Common examples of standard exceptions include:

  • NullPointerException: Thrown when you attempt to access a null object reference.

  • DmlException: Thrown for database operations (e.g., insert, update, delete) when records cannot be saved due to validation rules, triggers, or other issues.

  • LimitException: Thrown when you exceed governor limits set by Salesforce.

Custom: Examples of custom exceptions include:

  • CustomValidationException: Thrown when a custom validation rule is violated.

  • CustomBusinessRuleException: Thrown when a specific business rule is not met.

  • CustomIntegrationException: Thrown for errors related to external integrations.

3. Handling

Standard: Apex throw exceptions automatically by the system when specific error conditions occur. You don't need to define or throw them explicitly in your code.

Custom: Custom exceptions must be explicitly thrown in your code using the throw statement when the exceptional condition arises. You have control over when and where to throw them.

4. Customization

Standard: You cannot customize the error message or behavior of standard exceptions. They come with predefined error messages and behaviors.

Custom: With custom exceptions, you have full control over the exception class, including the error message, constructor parameters, and behavior. You can define custom methods and properties within the exception class.

5. Use Case

Standard: Standard exceptions are suitable for handling well-known and expected error scenarios in your code, such as null pointer checks, DML operations, and governor limit checks.

Custom: Custom exceptions are ideal for handling application-specific errors or conditions that cannot be adequately represented by standard exceptions. They allow you to provide context-specific error messages and define custom handling logic.

Best Practices for Custom Exceptions

Best Practices and some considerations to use custom exceptions in Apex are important to create efficient and maintainable error handling in your Salesforce applications. Here are some key considerations and best practices for deciding when to use custom exceptions:

  1. Complex Business Logic: Define custom exceptions for different business rules, making it easier to handle and communicate errors related to these rules.

  2. Unique Error Scenarios: Design custom exceptions to encapsulate the specific context and meaning of these unique error scenarios, providing clear and informative error messages.

  3. Granular Error Handling: Create custom exception classes for different types of errors to enable precise error identification and tailored error-handling logic.

  4. Consistency Across the Application: Establish naming conventions and patterns for your custom exceptions to ensure consistency across your application. For example, prefix custom exception names with "Custom" or use a common naming convention for related exceptions.

  5. Documenting Errors: Include descriptive comments or documentation for each custom exception class, explaining the error condition it represents and how it should be handled.

  6. Testing and Quality Assurance: Write unit tests that cover different error scenarios involving custom exceptions. This helps validate that the error-handling logic behaves correctly.

  7. Error Recovery Strategies: Define error recovery processes within your custom exception handling code, which may include logging, notifying users, rolling back transactions, or taking corrective actions.

  8. Avoid Overuse: Reserve custom exceptions for situations where they add significant value, such as complex business logic or unique error scenarios. Use standard exceptions for common and straightforward errors.