Sub topic 6
Throwing Exceptions Deliberately
This chapter assumes you can write basic Apex classes and methods, and that you know how try, catch, and finally blocks work. Until now, exceptions have mostly come from the platform. Here you will raise them yourself, so a method can refuse bad input or an impossible state instead of returning a wrong result.
Why throw an exception
A method has two ways to report a problem. It can return a special value such as null or -1, or it can throw an exception. Special values are easy to ignore. A caller who forgets to check null gets a NullPointerException somewhere else, far from the real cause. An exception can't be ignored in the same way. It stops the current code path and travels up the call stack until a catch block handles it.
Throw an exception when the method cannot do what its name promises. Validate input at the start of the method, so that bad data fails early and with a clear message.
The throw statement
You raise an exception with the throw keyword and an exception object. Every exception type has a constructor that takes a message.
public class DiscountDemo {
public static Decimal halve(Decimal amount) {
if (amount == null) {
throw new NullPointerException();
}
return amount / 2;
}
}You can throw built-in types such as NullPointerException or ListException. Choose a type whose name matches the problem. For problems specific to your business logic, a custom exception is clearer, and the next chapter covers it. The message you pass is what getMessage() returns later, so write it for the person who will read the log.
Writing useful messages
A good message says what was wrong and includes the offending value. Compare these two lines:
throw new InvoiceException('Invalid discount');throw new InvoiceException('Discount must be between 0 and 100: ' + percent);
The second one tells you the rule and the bad value without opening a debug log.
Throwing and the transaction
A thrown exception that nothing catches ends the whole transaction. Salesforce rolls back all DML done in that transaction. Callers can prevent this by catching the exception, but then they are responsible for deciding what state the data is in. The diagram shows the path.
A complete example
The method below validates its input and throws on bad values. The caller catches the exception and reports it.
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);
}
}try {
Decimal total = InvoiceService.applyDiscount(100, 150);
System.debug(total);
} catch (InvoiceService.InvoiceException e) {
System.debug('Rejected: ' + e.getMessage());
}The debug output is Rejected: Discount must be between 0 and 100: 150.
Common mistakes
- Throwing without a message. The log then shows only the type name, which makes diagnosis slow.
- Forgetting
new.throw InvoiceException('...')does not compile. You must create the object withnew. - Catching your own exception and returning
null. This turns a clear failure back into a silent one. - Throwing for expected outcomes. If "no record found" is normal, return an empty list or
nulland document it. Reserve exceptions for conditions the caller did not plan for.
Exercise
A method receives a list of Ids and cannot continue if the list is empty. Should it return null, or throw an exception? Write the line that throws a built-in exception with a useful message.
Show answer
It should throw, because returning null lets the caller continue with no data and fail later in a harder-to-trace place. For example: throw new ListException('Expected at least one Id but the list was empty');