doocs/leetcode · error · Error

Division by zero is not allowed

Error message

Division by zero is not allowed

What it means

In the LeetCode 2726 Calculator with method chaining, divide(value) guards against dividing by zero and throws Error('Division by zero is not allowed'). This is a deliberate domain guard because JavaScript/TypeScript would otherwise silently return Infinity (or NaN for 0/0), corrupting the chained result.

Source

Thrown at solution/2700-2799/2726.Calculator with Method Chaining/Solution.ts:25

    add(value: number): Calculator {
        this.x += value;
        return this;
    }

    subtract(value: number): Calculator {
        this.x -= value;
        return this;
    }

    multiply(value: number): Calculator {
        this.x *= value;
        return this;
    }

    divide(value: number): Calculator {
        if (value === 0) {
            throw new Error('Division by zero is not allowed');
        }
        this.x /= value;
        return this;
    }

    power(value: number): Calculator {
        this.x **= value;
        return this;
    }

    getResult(): number {
        return this.x;
    }
}

View on GitHub (pinned to f84f361dc4)

Solutions

  1. Check the divisor before calling divide: skip, clamp, or substitute a safe value
  2. Trace earlier chain steps: multiply(0) or subtract-to-zero feeding divide is a common chain bug
  3. Wrap the whole chain in try/catch if zero is a legitimate runtime input
  4. Validate inputs at the boundary (parse/validate user numbers before building the chain)

Example fix

// before
calc.add(10).divide(0).getResult(); // throws

// after
const d = getDivisor();
const result = d === 0 ? NaN : calc.add(10).divide(d).getResult();
Defensive patterns

Strategy: validation

Validate before calling

const divisor = computeDivisor();
if (divisor === 0) { /* skip/clamp */ } else { calc.divide(divisor); }

Type guard

const isSafeDivisor = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n !== 0;

Try / catch

try { const r = calc.add(10).divide(d).getResult(); } catch (e) { if ((e as Error).message.includes('Division by zero')) { /* handle */ } else throw e; }

Prevention

When it happens

Trigger: Calling new Calculator(...).divide(0), or chaining .divide(x) where x computes to 0 (e.g. a subtraction or modulo that yields 0 earlier in the chain).

Common situations: Chained expressions like calc.add(10).divide(0).getResult(); deriving the divisor from user input or previous operations without checking; porting code from languages where division by zero throws natively and forgetting the guard exists here too.

Related errors


AI-assisted analysis of doocs/leetcode@f84f361dc4 (2026-08-27). Data as JSON: /api/errors/a7106ed762738f52. Report an issue: GitHub.