doocs/leetcode · error · Exception

Can not divide by 0

Error message

Can not divide by 0

What it means

This is a hand-rolled guard clause in a LeetCode PHP solution for 'Divide Two Integers' (problem 29): divide($a, $b) explicitly throws new Exception('Can not divide by 0') when the divisor $b equals 0, because integer division is undefined for a zero divisor. PHP itself would normally surface this as a DivisionByZeroError (PHP 8+) or a warning + false (PHP 7), but this code pre-empts that with its own generic Exception. Since it throws the base Exception class, callers cannot narrowly catch it by type and must match on message or check arguments beforehand.

Source

Thrown at solution/0000-0099/0029.Divide Two Integers/Solution.php:10

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. Guard at the call site: only invoke divide($a, $b) when $b != 0, returning 0/skipping/handling the zero-divisor case explicitly before calling.
  2. If the LeetCode constraints guarantee $b != 0 (problem 29 guarantees divisor != 0), delete or ignore the throw branch — it is defensive dead code for the judged problem.
  3. Replace the generic Exception with a more specific error so callers can catch it precisely: throw new \DivisionByZeroError('Can not divide by 0') or define a DomainException subclass.
  4. If you actually want PHP's native behavior/interruption, remove the guard and let PHP 8+ raise DivisionByZeroError itself, catching that type upstream.

Example fix

// before
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception('Can not divide by 0');
    }
    // ...
}

// after (guard at call site + specific error type)
function safeDivide(int $a, int $b): int {
    if ($b === 0) {
        return 0; // or handle per your domain
    }
    return divide($a, $b);
}
// and inside divide(), if you keep the guard:
//   throw new \DivisionByZeroError('Can not divide by 0');
Defensive patterns

Strategy: validation

Validate before calling

if (!is_int($b) || $b === 0) {
    // skip, return a default, or surface an input error
    return 0;
}
$result = $solution->divide($a, $b);

Type guard

function isNonZeroDivisor(mixed $b): bool
{
    return is_numeric($b) && $b != 0;
}

Try / catch

try {
    $q = $solution->divide($a, $b);
} catch (\Exception $e) {
    if ($e->getMessage() !== 'Can not divide by 0') {
        throw $e; // rethrow unrelated exceptions
    }
    $q = 0; // zero-divisor fallback
}
// Prefer: catch (\DivisionByZeroError $e) if the guard is changed to throw that type.

Prevention

When it happens

Trigger: Calling divide($a, 0) with any $a — e.g. divide(10, 0), divide(0, 0), or divide(-2147483648, 0) — hits the `if ($b == 0)` branch at Solution.php:10 and throws immediately, before the $a == 0 and overflow checks run. It is also triggered when $b is a value that loosely equals 0 (e.g. the string '0' or 0.0) because the comparison uses == rather than ===.

Common situations: LeetCode-style judged solutions where edge-case tests pass 0 as the divisor; test harnesses doing fuzzing or property-based testing over random input pairs including 0; refactoring this helper into real code where the divisor comes from user input, a DB aggregate that can be 0, or an average/ratio calculation; PHP 7-to-8 migrations where division-by-zero changed from a warning to an EngineException and devs added explicit guards inconsistently.

Related errors


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