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.00divide(12, 0)throws, and the catch block printsDivide by zero: System.MathExceptiondivide(9, 3)after the try/catch →After catch: 3.00
Requirements:
- Inside
try, printNormal:with the result ofdivide(12, 3), then calldivide(12, 0). - Catch
MathException, not plainException. - In the catch block, print
Divide by zero:followed byerror.getTypeName(). - After the whole try/catch, print
After catch:with the result ofdivide(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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.