Custom Exception in Apex (Salesforce) – A Practical Guide


NSIQ Icon
August 22, 2025

custom exception in apex salesforce

Introduction

If you’ve ever built something in Apex, you’ve probably run into exceptions. These are unexpected “red flag” errors that pop up when your code hits a problem. Think of exceptions as Salesforce’s way of saying, “Hey, something’s not right here, and I can’t continue until you fix it.”

Apex, like most programming languages, has a built-in exception system. For example, if you try to insert a record with missing required fields, Salesforce throws a DmlException. If you divide by zero, you’ll see a MathException.

But here’s the thing: Not every error your application encounters is covered by Salesforce’s standard exceptions. Sometimes you need to define your own rules for what counts as an “exceptional” situation. That’s where custom exceptions come in.

Custom exceptions allow you to create meaningful, business-specific error messages. Instead of throwing a vague NullPointerException, you can throw something like InsufficientInventoryException, which makes it immediately clear what went wrong.

What is a Custom Exception in Apex?

In Apex, a custom exception is simply a class that extends the built-in Exception class. This gives you the flexibility to throw and catch errors that are tailored to your business logic.

Think of it as labelling your errors with names that make sense to your team and your system.

Creating a Custom Exception

Here’s the simplest way to define one:

public class InsufficientInventoryException extends Exception {}

That’s it! You’ve just created your first custom exception.

Now let’s see it in action:

public class InventoryService {
public static void reduceInventory(String productId, Integer quantity) {
Integer availableStock = 5; // Imagine this comes from a queryif (quantity > availableStock) {
throw new InsufficientInventoryException(
‘Not enough stock available. Requested: ‘ + quantity +
‘, Available: ‘ + availableStock
);
}// Continue with inventory reduction logic…
System.debug(‘Inventory reduced successfully!’);
}
}

And when you call this method:

try {
InventoryService.reduceInventory(‘P123’, 10);
} catch (InsufficientInventoryException ex) {
System.debug(‘Error: ‘ + ex.getMessage());
}

Instead of a generic Salesforce error, you get a message tailored to your scenario:

Error: Not enough stock available. Requested: 10, Available: 5

Real-World Use Cases for Custom Exceptions

Custom exceptions shine when you want clarity in your codebase. Here are a few practical scenarios:

1.Validation Failures Beyond Standard Rules

  • Example: A user tries to submit a loan request, but your business requires a minimum credit score of 700. Instead of just blocking the record, you throw a LowCreditScoreException.

2.Integration Failures

  • Example: You’re calling an external payment gateway, and it returns an invalid response. Throwing a PaymentGatewayException makes it obvious what went wrong.

Best Practices for Writing Custom Exceptions

Custom exceptions are powerful, but like any tool, they work best with a bit of discipline. Here are some tips:

  • Keep them descriptive: Name your exception classes after the problem they represent. InvalidDiscountCodeException is way better than CustomException1.
  • Use sparingly: Don’t create a new exception for every little hiccup. Reserve them for situations where clarity and debugging really matter.
  • Include helpful messages: When throwing an exception, add context like IDs, values, or conditions that will help someone troubleshoot later.
  • Catch selectively: Don’t just wrap everything in a blanket try-catch. Catch the exceptions you can actually handle, and let others bubble up if needed.

FAQ: Custom Exceptions in Apex 

1. Do I always need to create custom exceptions?

No. Use Salesforce’s standard exceptions like DmlException or NullPointerException when they make sense. Create custom exceptions only for business-specific logic.

2. Can I define multiple custom exceptions in one class?

Yes. In fact, it’s common to group related exceptions inside a service class for better organization.

3. What happens if I don’t catch a custom exception?

Just like standard exceptions, it will bubble up the call stack and ultimately cause the transaction to fail.

4. Can I add methods or fields to my custom exception?

Yes, since it’s just a class. You can add extra fields or methods if you need to pass more context with the exception.

Wrapping Up

Custom exceptions in Apex might sound like an advanced topic, but they’re really just a practical way to make your code more readable, maintainable, and business-friendly. Instead of sifting through vague error messages, you and your team can know exactly what went wrong at a glance.

So, the next time you’re building a complex business process in Salesforce, ask yourself:
“Would a custom exception make this error clearer?”

Chances are, the answer will be yes.

If your business is looking for expert Apex development, integrations, or custom Salesforce solutions, partnering with a Salesforce development company in USA can ensure your projects are built with precision and best practices.