Sub topic 7
Creating custom exception classes
This chapter assumes you can write Apex classes and methods, use try, catch, and finally, and throw an exception with throw. Earlier chapters covered the built-in types such as DmlException and QueryException. Here you will define your own.
Why define your own exception
Built-in exceptions describe failures in the platform: a query returned no rows, a DML statement was rejected. They don't describe failures in your business rules. If a discount is out of range, throwing a generic Exception with a message forces callers to catch everything. A custom exception gives that failure a name. Callers can then catch it and ignore unrelated errors.
A custom exception is useful for three reasons:
- Precise catching. A caller catches
InvoiceExceptionand lets other errors propagate. - Self-documenting code. A stack trace or debug log shows
InvoiceService.InvoiceException, which tells you where to look. - Extra data. You can attach fields such as an error code or a record Id.
The minimal definition
A custom exception is a class that extends Exception. Its name must end in Exception. The compiler rejects other names.
public class InvoiceService {
public class InvoiceException extends Exception {}
public static Decimal applyDiscount(Decimal amount, Decimal percent) {
if (percent < 0 || percent > 100) {
throw new InvoiceException('Discount must be between 0 and 100: ' + percent);
}
return amount - (amount * percent / 100);
}
}The class body is empty, yet new InvoiceException('message') works. Every class that extends Exception inherits these constructors automatically:
| Constructor | Use |
|---|---|
| `new MyException()` | No message. `getMessage()` returns `null`. |
| `new MyException('text')` | A message. |
| `new MyException(cause)` | Wraps another exception. The message is built from the cause. |
| `new MyException('text', cause)` | A message plus a wrapped cause. |
The cause constructors are covered in the chapter on wrapping and rethrowing. Because of the inherited constructors, you rarely need to write any code in the body.
Where to declare the class
You have two options.
- Inner class. Declared inside a service or utility class, as above. Callers refer to it as
InvoiceService.InvoiceException. This keeps the exception next to the code that throws it. - Top-level class. Declared in its own file, for example
BillingException.cls. Callers refer to it asBillingException. Use this when several classes share the exception.
An inner exception must be public or global for other classes to catch it. If you leave it private, code outside the class can't name it in a catch clause. That can leave you able to throw it but unable to catch it specifically.
Catching a custom exception
The caller uses the qualified name for an inner class.
try {
Decimal total = InvoiceService.applyDiscount(100, 150);
} catch (InvoiceService.InvoiceException e) {
System.debug('Invalid discount: ' + e.getMessage());
}The exception reports its own type through getTypeName(). For this example it returns InvoiceService.InvoiceException. Logs and error messages therefore show where the failure came from.
Building an exception hierarchy
A custom exception can extend another custom exception. This lets callers choose how specific to be. A broad base class catches everything your module throws, and subclasses catch individual cases.
public class BillingException extends Exception {}public class InvalidDiscountException extends BillingException {}public class PaymentDeclinedException extends BillingException {}Each class goes in its own file. A caller can now pick its level:
try {
BillingProcessor.run();
} catch (PaymentDeclinedException e) {
// Handle only declined payments, for example by notifying the customer.
System.debug('Declined: ' + e.getMessage());
} catch (BillingException e) {
// Any other billing failure.
System.debug('Billing problem: ' + e.getMessage());
}Catch order matters. Apex checks catch blocks from top to bottom and runs the first match. Put the subclass first and its parent after it. If BillingException came first, the compiler would report that the PaymentDeclinedException block can never be reached.
Keep hierarchies shallow. One base class per module and a handful of subclasses is plenty. Deep trees make it hard to know which type a method can throw.
Adding data to an exception
Sometimes a message string is not enough. A caller may want an error code or the Id of the failing record. Add fields and a constructor, and call this(message) first so the message is set up correctly.
public class PaymentDeclinedException extends BillingException {
public String declineCode { get; private set; }
public Id invoiceId { get; private set; }
public PaymentDeclinedException(String message, String declineCode, Id invoiceId) {
this(message);
this.declineCode = declineCode;
this.invoiceId = invoiceId;
}
}Usage:
try {
throw new PaymentDeclinedException('Card was declined', 'INSUFFICIENT_FUNDS', null);
} catch (PaymentDeclinedException e) {
System.debug(e.declineCode + ': ' + e.getMessage());
}Here the invoice Id is null only to keep the example runnable on its own. In real code you would pass the record's Id.
When you write your own constructor, the inherited ones that take a message or a cause are still available. Calling this(message) from your constructor routes through the inherited one. If you skip that call, getMessage() can return null, which is a common source of confusing logs.
Make the extra fields read-only from outside with private set. An exception describes something that already happened, so callers should not change it.
Writing good messages
The message is usually the only thing a developer sees in a log. Write it for that reader:
- State what was wrong and include the offending value:
'Discount must be between 0 and 100: 150'is better than'Invalid input'. - Include identifiers such as record Ids when they help locate the failure.
- Never include secrets, tokens, or personal data. Messages end up in debug logs, email notifications, and sometimes in the user interface.
- Keep user-facing text separate. A message written for a developer is rarely right for an end user. The chapter on Lightning components shows how to translate between them.
Common mistakes
- Wrong name.
InvoiceError extends Exceptiondoes not compile. The name must end inException. - Catching only the parent.
catch (BillingException e)also catches every subclass. That is often what you want, but it can hide a case that needs different handling. Add a more specific block above it. - A private inner class. Callers outside the enclosing class can't catch it by name, so they fall back to catching
Exception. - Forgetting
this(message). A custom constructor that doesn't call it leaves the message empty. - Using exceptions for normal flow. Throw for unexpected or invalid states. If a missing record is routine, check for it with an
ifstatement instead.
Checking your exception in a test
A test should confirm that the code throws your exception and that the message is useful.
@IsTest
private class InvoiceServiceTest {
@IsTest
static void rejectsInvalidDiscount() {
try {
InvoiceService.applyDiscount(100, 150);
Assert.fail('Expected InvoiceException was not thrown');
} catch (InvoiceService.InvoiceException e) {
Assert.isTrue(e.getMessage().contains('between 0 and 100'));
}
}
}Assert.fail throws an AssertException. The catch block does not match it, so the test fails if the method returns normally. The later testing chapter covers this pattern in more detail.
Exercise
You define public class ShippingException extends Exception {} and a subclass public class AddressException extends ShippingException {}. A method can throw either. In a caller, you write a catch (ShippingException e) block followed by a catch (AddressException e) block. What happens, and how do you fix it?
Show answer
The code does not compile. ShippingException is the parent, so its block would catch every AddressException and the second block could never run. Put the subclass first: catch (AddressException e) { ... } catch (ShippingException e) { ... }. Apex runs the first matching block from top to bottom, so the more specific handler must come first.
Exercise
A custom exception StockException has a field sku and a constructor StockException(String message, String sku) that sets this.sku = sku but never calls this(message). What problem can this cause, and what is the fix?
Show answer
getMessage() can return null because the message was never set through the inherited constructor, so logs and tests that read the message show nothing useful. The fix is to call this(message); as the first line of the constructor, then assign this.sku = sku;.