doocs/leetcode · error · Error
Division by zero is not allowed
Error message
Division by zero is not allowed
What it means
README (Chinese) copy of the LeetCode 2726 Calculator: divide(value) throws Error('Division by zero is not allowed') when value === 0, guarding the chained API from silently producing Infinity/NaN. The chain returns this from every method, so the throw aborts the entire chain before getResult().
Source
Thrown at solution/2700-2799/2726.Calculator with Method Chaining/README.md:119
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;
}
}
```
<!-- tabs:end -->
View on GitHub (pinned to f84f361dc4)
Solutions
- Validate the divisor before chaining: skip or substitute when 0
- Check intermediate chain values that feed the divisor
- Wrap chains in try/catch when zero is possible at runtime
- Parse and validate numeric inputs at the API boundary
Example fix
// before new Calculator(20).divide(0).getResult(); // throws // after const c = new Calculator(20); const r = d !== 0 ? c.divide(d).getResult() : NaN;
Defensive patterns
Strategy: validation
Validate before calling
if (d === 0) { /* choose fallback */ } else { calc.divide(d); } Type guard
const isNonZeroNumber = (v: unknown): v is number => typeof v === 'number' && v !== 0;
Try / catch
try { calc.add(10).divide(d).getResult(); } catch (e) { if ((e as Error).message === 'Division by zero is not allowed') { /* fallback */ } else throw e; } Prevention
- Validate computed divisors
- Test chains with 0
- Parse inputs with Number() and check
When it happens
Trigger: new Calculator(10).divide(0).getResult(); or a computed divisor that evaluates to 0 mid-chain (e.g. after subtract(x) that zeroes the stored value used as the divisor elsewhere).
Common situations: Practicing method chaining with edge inputs; divisors sourced from parsed user input defaulting to 0; misunderstanding that the guard uses === so '0' (string) would not throw but 0 does (and vice versa in JS 0 == '0'); building fluent APIs and studying where guards belong.
Related errors
- Division by zero is not allowed
- Division by zero is not allowed
- Can not divide by 0
- Can not divide by 0
- Not Equal
AI-assisted analysis of doocs/leetcode@f84f361dc4 (2026-08-27).
Data as JSON: /api/errors/4b81aacd54ba756b.
Report an issue: GitHub.