doocs/leetcode · error · Exception
Can not divide by 0
Error message
Can not divide by 0
What it means
English README variant of the same PHP LeetCode 29 solution: divide($a, $b) throws Exception('Can not divide by 0') when $b == 0. It exists because the algorithm assumes a non-zero divisor per problem constraints and guards the boundary explicitly before performing subtraction-based division.
Source
Thrown at solution/0000-0099/0029.Divide Two Integers/README_EN.md:267
}
return sign ? ans : -ans;
}
}
```
#### PHP
```php
class Solution {
/**
* @param integer $a
* @param integer $b
* @return integer
*/
function divide($a, $b) {
if ($b == 0) {
throw new Exception('Can not divide by 0');
} elseif ($a == 0) {
return 0;
}
if ($a == -2147483648 && $b == -1) {
return 2147483647;
}
$sign = $a < 0 != $b < 0;
$a = abs($a);
$b = abs($b);
$ans = 0;
while ($a >= $b) {
$x = $b;
$cnt = 1;
while ($a >= $x << 1) {
$x <<= 1;
$cnt <<= 1;
}View on GitHub (pinned to f84f361dc4)
Solutions
- Guard the call site: if ($b == 0) return a sentinel or error instead of calling
- Filter zero divisors out of test-case generators
- Wrap in try/catch (Exception) if the value legitimately comes from untrusted input
- Remember return 0 shortcut when $a == 0 — only $b == 0 throws
Example fix
// before
echo divide(7, 0); // throws 'Can not divide by 0'
// after
function safeDivide(int $a, int $b): ?int {
return $b === 0 ? null : divide($a, $b);
} Defensive patterns
Strategy: validation
Validate before calling
$b = (int)$input; if ($b === 0) { fwrite(STDERR, "divisor must be non-zero\n"); exit(1); } divide($a, $b); Type guard
function isNonZeroDivisor(mixed $v): bool { return is_int($v) && $v !== 0; } Try / catch
try { divide(7, $b); } catch (Exception $e) { /* 'Can not divide by 0' */ } Prevention
- Filter zero divisors from test generators
- Check $b before calling
- Only $b==0 throws; $a==0 short-circuits to 0
When it happens
Trigger: Running the documented snippet with $b = 0, $b = '0', or $b = 0.0 (loose == matches all); test scripts that sweep divisors including zero.
Common situations: Copy-pasting the README code into a local runner and passing edge-case inputs; PHP 8 strictness changes making unguarded division fatal; assuming the overflow branch (PHP_INT_MIN / -1) is the only special case to handle.
Related errors
- Can not divide by 0
- Can not divide by 0
- Division by zero is not allowed
- Division by zero is not allowed
- Division by zero is not allowed
AI-assisted analysis of doocs/leetcode@f84f361dc4 (2026-08-27).
Data as JSON: /api/errors/686d0f0e16132c74.
Report an issue: GitHub.