ApexSensei

Drills › Think in classes

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, and apply(200.00, 50) → Exactly 50: 100.00
  • apply(200.00, 51) throws, and the catch prints Over limit: 51% exceeds 50%
  • apply(200.00, -5) throws, and the catch prints Below zero: -5% is below 0%

Requirements:

  1. Declare DiscountRangeException as a custom exception.
  2. In apply, throw it when the percent is above 50 or below 0. Build the message from the percent, like 51% exceeds 50% or -5% is below 0%.
  3. Otherwise return the discounted amount, rounded to 2 places with setScale(2, RoundingMode.HALF_UP).
  4. Print Valid: and Exactly 50: from the first two calls.
  5. Call it with 51 and with -5, each in a try/catch for DiscountRangeException. Print Over limit: and Below zero:, each followed by error.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.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Recover from division by zero