Sub topic 6
Throwing Exceptions Deliberately
This chapter assumes you can write Apex classes and methods and use try, catch, and finally blocks. You should also know that an uncaught exception rolls back the current transaction. Earlier chapters covered how the runtime throws exceptions for you. This chapter covers how your own code throws them on purpose.
Why throw an exception yourself
A method can receive input it cannot work with. It then has three choices:
- Return a made-up value, such as
nullor0. - Continue and let a later line fail in a confusing way.
- Stop immediately and tell the caller what went wrong.
The third choice is usually best, and the throw statement does it. Throwing an exception does four things:
- It stops the current method at once.
- It carries a message and a stack trace back up the call chain.
- It leaves the decision about how to respond to the caller, which has more context than your method.
- If nobody catches it, it rolls back the transaction, so bad data is not saved.
The throw statement
The syntax is throw followed by an exception object. You create the object with new:
throw new InvoiceService.InvoiceException('Discount must be between 0 and 100');Three rules apply:
- You can only throw an instance of
Exceptionor one of its subclasses. You cannot throw a string or a custom data class. - The exception object is created before it is thrown. You can set properties on it between the two steps.
- Statements after a
throwin the same block never run.
Here is a complete class that validates input with guard clauses:
public class InvoiceService {
public class InvoiceException extends Exception {}
public static Decimal applyDiscount(Decimal amount, Decimal percent) {
if (amount == null || percent == null) {
throw new InvoiceException('Amount and percent are required');
}
if (amount < 0) {
throw new InvoiceException('Amount cannot be negative: ' + amount);
}
if (percent < 0 || percent > 100) {
throw new InvoiceException('Discount must be between 0 and 100: ' + percent);
}
return amount - (amount * percent / 100);
}
}Each check is a guard clause. It rejects one kind of bad input at the top of the method, so the calculation at the bottom can assume valid values. Without the null check, amount < 0 would throw a NullPointerException. That exception would say nothing about which input was wrong.
A caller handles the exception like any other:
try {
Decimal total = InvoiceService.applyDiscount(200, 150);
System.debug(total);
} catch (InvoiceService.InvoiceException e) {
System.debug('Rejected: ' + e.getMessage());
}This prints Rejected: Discount must be between 0 and 100: 150.
Writing useful messages
The message is often the only clue a developer or admin gets, so write it for someone who cannot see your code. A good message follows these guidelines:
- It names the rule that was broken.
- It includes the offending value, as the example above does with
percent. - It includes an identifier, such as a record Id, when the failure involves a record.
- It leaves out secrets, such as tokens, passwords, and personal data. Exception messages end up in debug logs and sometimes in the user interface.
Compare these two messages for the same failure:
| Weak message | Useful message |
|---|---|
| `Invalid input` | `Discount must be between 0 and 100: 150` |
| `Error` | `Opportunity 006xx0000012345 has no line items; cannot calculate total` |
Throwing built-in exception types
You can also throw many of Apex's built-in exception types. Their constructors take a message in the same way:
public class ListHelper {
public static Account firstAccount(List<Account> accounts) {
if (accounts == null || accounts.isEmpty()) {
throw new ListException('Expected at least one account');
}
return accounts[0];
}
}Reuse a built-in type only when its name matches the failure. A caller who catches DmlException expects a failed database operation. If you throw one for a validation rule, that caller may handle it wrongly. When no built-in type fits, define a custom exception. The next chapter covers that.
Adding data to an exception
A custom exception is an ordinary class, so it can carry fields. Callers can then react to the failure without parsing the message text. This example needs no custom constructor:
public class ImportService {
public class ImportException extends Exception {
public Integer rowNumber;
}
public static void validateRow(Integer rowNumber, String email) {
if (String.isBlank(email)) {
ImportException ex = new ImportException('Email is required');
ex.rowNumber = rowNumber;
throw ex;
}
}
}Here the code builds the exception, sets rowNumber, and then throws it. A caller can read e.rowNumber in its catch block and report the failing row.
Throwing from inside catch and finally
You can throw from a catch block. This is how you rethrow, either the same exception or a new one:
try {
ImportService.validateRow(3, '');
} catch (ImportService.ImportException e) {
System.debug('Logging row ' + e.rowNumber);
throw e;
}A bare throw e; sends the original exception, with its original message and type, to the caller. Wrapping in a new exception type is a separate technique. A later chapter covers it.
Be careful with throw inside a finally block. The finally block runs even after an exception, and a new exception thrown there replaces the one that was already in flight. The original failure is lost. Keep finally blocks to cleanup work that cannot fail.
When to throw and when not to
Throwing is not always the right tool. Use this table to decide:
| Situation | Better approach |
|---|---|
| Caller passed a value your method cannot accept | Throw an exception |
| A required step failed and the work cannot continue | Throw an exception |
| A missing result is a normal outcome, such as "no matching record" | Return `null` or an empty list and document it |
| One record in a trigger failed validation, but others may proceed | Call `addError` on that record |
| You want to log a problem but continue | Catch, log, and do not rethrow |
Do not use exceptions for ordinary control flow. If a branch is expected to happen often, an if statement says so more clearly than a catch block does.
Common mistakes
- Forgetting
throw. Writingnew InvoiceException('bad');on its own line creates an object and discards it. Nothing is thrown, and the method continues. - Naming a custom exception without the
Exceptionsuffix. The class name must end inException, or the code will not compile. - Throwing generic messages.
throw new InvoiceException('Error')forces the next developer to read your code to learn what happened. - Swallowing and throwing nothing. An empty catch block hides the failure. Either handle it, log it, or rethrow it.
- Throwing where
addErrorfits. In a trigger, an exception aborts the whole batch of records.addErrorblocks only the record that failed.
Summary
You throw with throw new SomeException('message'). The object must be an Exception subclass, and the throw stops the method at once. Good messages name the broken rule and include the bad value. Custom exceptions can carry fields, and built-in types fit only when their name matches the failure. A throw inside finally replaces any exception already in flight. Throw when the caller should decide what to do, and return a value when a missing result is normal.
Exercise
The method below is meant to reject a null Account, but it does not. Find the bug and fix it so the method throws a ListException with a message that names the problem. What does the caller see if the bug is left in place?
public static String accountName(Account acc) {
if (acc == null) {
new ListException('Account is required');
}
return acc.Name;
}
Show answer
The bug is that throw is missing. The line only creates an exception object and discards it, so the method continues. With the bug in place, the caller gets a NullPointerException ("Attempt to de-reference a null object") from acc.Name, which does not say which input was wrong. The fix is throw new ListException('Account is required');. After that change the method stops at the guard and the caller sees the clear message. A custom exception would be a better fit than ListException, because the failure has nothing to do with lists.
Exercise
A method calls Database.rollback(sp) and then runs throw new BillingException('Failed'); inside a try block. The finally block contains throw new BillingException('Cleanup failed');. Which message does the caller receive, and why?
Show answer
The caller receives 'Cleanup failed'. The finally block always runs, and an exception thrown inside it replaces the exception already in flight. The original 'Failed' exception is lost. To avoid this, keep finally blocks free of code that can throw.