System.MathException: Divide by zero
What does this error mean?
Apex throws System.MathException when integer or decimal division by zero is attempted. This is common in reporting and rollup logic where the divisor is derived from a COUNT() or SUM() aggregate that returns zero for a particular group — for example, calculating a win rate where no opportunities have been closed in a given period.
Common Causes
1. COUNT() aggregate returns zero for a group
A win-rate formula like wonCount / totalCount where totalCount is zero for a particular owner or period — data-dependent and difficult to catch in testing.
2. SUM() returns zero or null
Dividing by a SUM() result that is null (no matching records) or zero (all values are 0) without null/zero checking.
How to Fix It
Solution 1: Guard the divisor with a null/zero check
// ❌ BAD — throws if totalCount is 0
Decimal winRate = wonCount / totalCount;
// ✅ GOOD — guard against zero
Decimal winRate = (totalCount != null && totalCount != 0)
? (wonCount / totalCount) * 100
: 0;
// ✅ Pattern for aggregate result
for (AggregateResult ar : [
SELECT OwnerId, COUNT() total, SUM(Amount) revenue
FROM Opportunity
GROUP BY OwnerId
]) {{
Integer total = (Integer) ar.get('total');
Decimal revenue = (Decimal) ar.get('revenue');
Decimal avg = (total != null && total > 0)
? revenue / total
: 0;
System.debug('Avg deal: ' + avg);
}}
Pro Tip: SUM() on a group with no matching records returns null in SOQL, not 0. Always cast aggregate results to the expected type and check for null before checking for zero — they are two different failure modes.