Sub topic 7
Creating custom exception classes
This chapter assumes you can write Apex classes and methods and use try, catch, and finally. You should also know the built-in exceptions such as DmlException and QueryException. Here you will define your own exception type and throw it.
Why define your own
Built-in exceptions describe platform failures. They don't describe rules in your application, such as "a discount must be between 0 and 100". If you throw a generic Exception for that rule, callers can't tell it apart from other failures. A custom exception gives the rule its own type. Callers can then catch that type and ignore the others.
Defining one
A custom exception is a class that meets three requirements:
- It extends
Exception. - Its name ends in
Exception. - It can be a top-level class or an inner class.
The body can be empty. Apex gives every custom exception four constructors automatically, so you don't write them:
| Constructor call | Effect |
|---|---|
| `new MyException()` | No message |
| `new MyException('text')` | Sets the message |
| `new MyException(cause)` | Wraps another exception |
| `new MyException('text', cause)` | Sets the message and wraps another exception |
Throwing it
This service declares an inner exception and throws it when the input is invalid.
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 caller catches the type by its qualified name. You can run this in Anonymous Apex.
try {
Decimal total = InvoiceService.applyDiscount(100, 150);
System.debug(total);
} catch (InvoiceService.InvoiceException e) {
System.debug('Rejected: ' + e.getMessage());
}An inner class is referenced as OuterClass.InnerException. A top-level exception needs its own file and is referenced by its name alone.
Writing good messages
The message is the first thing a developer sees in a debug log. Include the rule that was broken and the offending value, as the example does with percent. Don't put secrets or full record contents in a message, because messages end up in logs and sometimes in the UI.
Common errors
- A name that doesn't end in
Exception. The class fails to compile. - Catching the wrong name. Catching
InvoiceExceptionwhen the type isInvoiceService.InvoiceExceptionfails to compile from outside the class. - Throwing without a message.
getMessage()returnsnull, and the log is hard to read. - Creating the exception and forgetting
throw.new InvoiceException('x');on its own does nothing.
Exercise
You write public class DiscountError extends Exception {} and try to save it. What goes wrong, and how do you fix it?
Show answer
The save fails because the name of a custom exception must end in Exception. Rename the class to DiscountException. Also confirm the class actually extends Exception.
Exercise
Add a check to applyDiscount so that a null amount throws an InvoiceException with the message "Amount is required". Which constructor do you use?
Show answer
Add if (amount == null) { throw new InvoiceException('Amount is required'); } before the discount check. It uses the constructor that takes a String message, which Apex provides automatically.