{"record":{"id":"c3d77e0502f082f2","repo":"doocs/leetcode","slug":"can-not-divide-by-0-c3d77e","errorCode":null,"errorMessage":"Can not divide by 0","messagePattern":"Can not divide by 0","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"solution/0000-0099/0029.Divide Two Integers/Solution.php","lineNumber":10,"sourceCode":"class Solution {\n    /**\n     * @param integer $a\n     * @param integer $b\n     * @return integer\n     */\n\n    function divide($a, $b) {\n        if ($b == 0) {\n            throw new Exception('Can not divide by 0');\n        } elseif ($a == 0) {\n            return 0;\n        }\n        if ($a == -2147483648 && $b == -1) {\n            return 2147483647;\n        }\n        $sign = $a < 0 != $b < 0;\n\n        $a = abs($a);\n        $b = abs($b);\n        $ans = 0;\n        while ($a >= $b) {\n            $x = $b;\n            $cnt = 1;\n            while ($a >= $x << 1) {\n                $x <<= 1;\n                $cnt <<= 1;\n            }","sourceCodeStart":1,"sourceCodeEnd":28,"githubUrl":"https://github.com/doocs/leetcode/blob/f84f361dc403a65c4c031f6e0774297cc377f00a/solution/0000-0099/0029.Divide Two Integers/Solution.php#L1-L28","documentation":"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.","triggerScenarios":"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 ===.","commonSituations":"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.","solutions":["Guard at the call site: only invoke divide($a, $b) when $b != 0, returning 0/skipping/handling the zero-divisor case explicitly before calling.","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.","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.","If you actually want PHP's native behavior/interruption, remove the guard and let PHP 8+ raise DivisionByZeroError itself, catching that type upstream."],"exampleFix":"// before\nfunction divide($a, $b) {\n    if ($b == 0) {\n        throw new Exception('Can not divide by 0');\n    }\n    // ...\n}\n\n// after (guard at call site + specific error type)\nfunction safeDivide(int $a, int $b): int {\n    if ($b === 0) {\n        return 0; // or handle per your domain\n    }\n    return divide($a, $b);\n}\n// and inside divide(), if you keep the guard:\n//   throw new \\DivisionByZeroError('Can not divide by 0');","handlingStrategy":"validation","validationCode":"if (!is_int($b) || $b === 0) {\n    // skip, return a default, or surface an input error\n    return 0;\n}\n$result = $solution->divide($a, $b);","typeGuard":"function isNonZeroDivisor(mixed $b): bool\n{\n    return is_numeric($b) && $b != 0;\n}","tryCatchPattern":"try {\n    $q = $solution->divide($a, $b);\n} catch (\\Exception $e) {\n    if ($e->getMessage() !== 'Can not divide by 0') {\n        throw $e; // rethrow unrelated exceptions\n    }\n    $q = 0; // zero-divisor fallback\n}\n// Prefer: catch (\\DivisionByZeroError $e) if the guard is changed to throw that type.","preventionTips":["Validate the divisor before every call: skip, clamp, or prompt when it is 0.","Use strict comparison ($b === 0) so values like null or '' don't loosely match 0.","Throw/catch a specific type (\\DivisionByZeroError or a domain exception) instead of generic Exception so zero-divisor errors are distinguishable.","In test suites, filter zero divisors out of generated inputs (e.g. only fuzz $b in [-2^31, -1] ∪ [1, 2^31]) rather than catching the exception."],"tags":["php","division-by-zero","arithmetic","guard-clause","leetcode"],"backgroundTag":"division-by-zero","analyzedSha":"f84f361dc403a65c4c031f6e0774297cc377f00a","analyzedAt":"2026-08-27T04:29:31.522Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}