Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
All errors
Apex

System.MathException: Divide by 0

An Integer division by zero. Different from Decimal — `Decimal / 0` returns Infinity in some contexts. Always guard the denominator before dividing, especially with computed denominators from queries.

Also seen asMathException: Divide by 0·Divide by zero·MathException Apex·Arithmetic exception

Apex Integer arithmetic is strict: Integer / 0 throws. Decimal arithmetic is more permissive but you still don't want unguarded divisions in your business logic.

What throws and what doesn't

Integer i = 5 / 0;          // ❌ MathException: Divide by 0
Decimal d = 5.0 / 0;        // ❌ MathException too — Apex Decimal also throws
Decimal d2 = 5.0 / 0.0;     // ❌ same
Double dd = 5.0 / 0.0;      // returns Infinity (Double = IEEE 754)
Decimal mod = 5 / 0;        // throws — modulo by zero same family

Apex's Decimal type doesn't follow IEEE 754. Only Double does. So the cure isn't switching types — it's checking the denominator.

The defensive pattern

public static Decimal safeDivide(Decimal numerator, Decimal denominator) {
    if (denominator == null || denominator == 0) return 0;   // or null, or throw a domain error
    return numerator / denominator;
}

For computed denominators from queries, treat zero as "no data" not as "really zero":

Integer total = [SELECT COUNT(Id) total FROM Account].total;
Decimal avg = total > 0 ? (Decimal) revenue / total : 0;

A common source: roll-up summary fields

A formula field like Total_Children__c / Total_Parents__c is fine until one parent has zero children. Then the formula throws — but Salesforce silently shows #Error! in the UI, not the user-friendly zero you probably wanted.

Fix: wrap in IF:

IF(Total_Parents__c > 0, Total_Children__c / Total_Parents__c, 0)

A subtler case: chained calculations

Decimal a = total / b;
Decimal c = a / d;

If total is 0 and b is 0, the first line throws. Even if you guard b, total being 0 might propagate to make later divisions weird. Add the guard at the right layer — usually as close to the final use as possible.

When MathException isn't divide-by-zero

MathException covers a few other cases:

  • Math.sqrt(-1) returns NaN-equivalent and may throw on some Apex versions
  • Overflow on Integer math: Integer.MAX_VALUE + 1 wraps in some contexts but throws in others; use Long for accumulator math
  • Decimal.divide(other, scale, roundingMode) throws if scale is invalid

The exception message tells you which. Read it before assuming it's divide-by-zero.

Related dictionary terms