doocs/leetcode · error · Exception

Can not divide by 0

Error message

Can not divide by 0

What it means

PHP solution for LeetCode 29 (Divide Two Integers) explicitly throws Exception('Can not divide by 0') when the divisor $b is 0, because the problem guarantees non-zero divisors but a robust guard is included. PHP itself would throw a DivisionByZeroError for the modulo/intdiv path anyway; this guard gives a controlled message and also handles the $a == -2147483648 && $b == -1 overflow case.

Source

Thrown at solution/0000-0099/0029.Divide Two Integers/README.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

  1. Validate the divisor before calling: if ($b == 0) handle gracefully (return 0, null, or an error)
  2. Check where $b originates (query param, config) and reject/filter zero early
  3. Catch Exception around the call only as a last-resort safety net
  4. Note the special case: divide(PHP_INT_MIN, -1) returns PHP_INT_MAX by design

Example fix

// before
divide(10, (int) $_GET['b']); // throws when b=0

// after
$b = (int) $_GET['b'];
if ($b === 0) { http_response_code(400); exit('divisor must be non-zero'); }
divide(10, $b);
Defensive patterns

Strategy: validation

Validate before calling

if ($b == 0) { return null; /* or throw a domain-specific error */ }
return divide($a, $b);

Type guard

function isNonZeroInt($v): bool { return is_numeric($v) && (int)$v !== 0; }

Try / catch

try { divide($a, $b); } catch (Exception $e) { if ($e->getMessage() === 'Can not divide by 0') { /* handle */ } else throw $e; }

Prevention

When it happens

Trigger: Calling divide($a, 0) directly, or with $b arriving from user input/configuration that evaluates to 0 (including '0' or 0.0 due to PHP's loose ==).

Common situations: Test harnesses passing 0 as the divisor; values parsed from request parameters defaulting to 0; porting the algorithm where callers assume the constraint is enforced upstream; PHP 8 environments where the engine's own DivisionByZeroError would otherwise surface.

Related errors


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