Reject an invalid discount
Think in classes · Intermediate · 18 min · Runs in your Salesforce Developer org · Free
Scenario. A quoting service needs a recognizable failure type when a discount breaks policy.
Throw a custom exception when a discount is outside 0 to 50 percent, and print its message.
What you will learn
A custom exception gives a business rule its own error type. Declare it with extends Exception. Throw it with new and a message, then catch that type where you call the method.
class LimitException extends Exception {}
throw new LimitException(amount + ' is over the limit');
In the catch block, error.getMessage() returns that message.
Gotcha. Naming the class is not enough. You must throw new an instance.
The task
Make a discount policy throw a custom exception for percentages outside 0 to 50, and print the error message when it does.
Examples:
apply(200.00, 25)→Valid: 150.00, andapply(200.00, 50)→Exactly 50: 100.00apply(200.00, 51)throws, and the catch printsOver limit: 51% exceeds 50%apply(200.00, -5)throws, and the catch printsBelow zero: -5% is below 0%
Requirements:
- Declare
DiscountRangeExceptionas a custom exception. - In
apply, throw it when the percent is above 50 or below 0. Build the message from the percent, like51% exceeds 50%or-5% is below 0%. - Otherwise return the discounted amount, rounded to 2 places with
setScale(2, RoundingMode.HALF_UP). - Print
Valid:andExactly 50:from the first two calls. - Call it with 51 and with -5, each in a try/catch for
DiscountRangeException. PrintOver limit:andBelow zero:, each followed byerror.getMessage().
Starter code
class DiscountPolicy {
public Decimal apply(Decimal amount, Decimal percent) {
return amount;
}
}
DiscountPolicy policy = new DiscountPolicy();
System.debug('Valid: ' + policy.apply(200.00, 25));
System.debug('Exactly 50: ' + policy.apply(200.00, 50));
When it passes
Valid discounts are worked out and rounded, exactly 50% is allowed, and 51% and -5% are caught as DiscountRangeException with a message that names the percent.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.