ApexSensei

Drills › Think in classes

Recover from division by zero

Think in classes · Intermediate · 15 min · Runs in your Salesforce Developer org · Free

Scenario. A reporting calculation should flag bad input without stopping the rest of the anonymous Apex run.

Call a calculator inside try/catch, catch the divide-by-zero MathException, and keep going.

What you will learn

try holds code that might fail. If a line throws, Apex skips the rest of try and runs the matching catch block. Code after the whole try/catch still runs.

try {
    Decimal ratio = total / count;
} catch (MathException error) {
    System.debug(error.getTypeName());
}

Dividing by zero throws MathException. getTypeName() returns the exception's type as text.

Gotcha. Catch the specific type. Plain Exception also hides bugs you did not expect.

The task

Wrap calls to a calculator in try/catch so dividing by zero is caught and later code still runs.

Examples:

  • divide(12, 3) → Normal: 4.00
  • divide(12, 0) throws, and the catch block prints Divide by zero: System.MathException
  • divide(9, 3) after the try/catch → After catch: 3.00

Requirements:

  1. Inside try, print Normal: with the result of divide(12, 3), then call divide(12, 0).
  2. Catch MathException, not plain Exception.
  3. In the catch block, print Divide by zero: followed by error.getTypeName().
  4. After the whole try/catch, print After catch: with the result of divide(9, 3).

Starter code

class RatioCalculator {
    public Decimal divide(Decimal numerator, Decimal denominator) {
        return (numerator / denominator).setScale(2);
    }
}

RatioCalculator calculator = new RatioCalculator();
try {
} catch (MathException error) {
}

When it passes

The normal result prints, dividing by zero is caught as System.MathException, and a later calculation still runs.

Try this drill free

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

‹ Route Cases with an enum · Reject an invalid discount ›