doocs/leetcode · error · Error
Division by zero is not allowed
Error message
Division by zero is not allowed
What it means
English README copy of the LeetCode 2726 Calculator divide guard: if (value === 0) throw new Error('Division by zero is not allowed') before performing this.x /= value and returning this. It converts what would be silent IEEE-754 Infinity into an explicit, catchable failure inside the fluent chain.
Source
Thrown at solution/2700-2799/2726.Calculator with Method Chaining/README_EN.md:120
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
- Pre-check value === 0 (and consider '0' after Number()) before calling divide
- Restructure the chain so the divisor is validated first
- Catch the error around the whole chain and report which step failed
- Add unit tests for divide(0) to lock in the intended behavior
Example fix
// before
calc.add(5).divide(0).getResult(); // throws
// after
if (d === 0) throw new RangeError('bad divisor');
calc.add(5).divide(d).getResult(); Defensive patterns
Strategy: validation
Validate before calling
const d = Number(rawDivisor);
if (!Number.isFinite(d) || d === 0) throw new RangeError('invalid divisor');
calc.divide(d); Type guard
function isSafeDivisor(v: unknown): v is number { return typeof v === 'number' && v !== 0; } Try / catch
try { const out = calc.divide(d).getResult(); } catch (e) { if ((e as Error).message.includes('Division by zero')) handleBadDivisor(); else throw e; } Prevention
- Check divisors before building chains
- Validate at API boundaries
- Add divide(0) unit tests
When it happens
Trigger: .divide(0) anywhere in a chain; .divide(n % k) style expressions where the modulo can be 0; divisors read from external input without validation.
Common situations: Following the tutorial and testing edge cases; refactoring imperative calculators into chains and forgetting zero handling; demoing fluent interfaces where one bad link kills the chain; mixing string '0' vs number 0 when parsing input (=== is strict).
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/233c2433aa95b8df.
Report an issue: GitHub.