PHP, How to catch a division by zero?

PHP, How to catch a division by zero?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why eval Swallows Division by Zero Errors in PHP

Attempting to execute dynamic mathematical expressions with eval() is a common pattern in legacy code or specific parser implementations, but handling control flow within that context often trips developers up. The core issue isn't just about catching exceptions; it's about the fundamental architecture of how eval() interacts with the current stack and scope.

When you attempt to wrap the expression inside a try-catch block directly inside the string passed to eval(), such as eval("try{ \$result = $expresion;}catch(Exception \$e){\$result = 0;}");, PHP parses the entire string as a new script context. However, the syntax for defining exception handlers in that specific string depends entirely on how the expression is constructed. If your parser builds valid PHP code strings, the try-catch block should technically be parseable. The reason this often fails or behaves unexpectedly is usually not the eval function itself rejecting the logic, but rather that the syntax inside the string might not match the expected structure for the specific version of PHP running, or the exception isn't being thrown as a standard Exception object in the way anticipated by older parser implementations.

The most robust and predictable solution involves moving the error handling outside the evaluated scope entirely. You cannot reliably catch a DivisionByZeroError (or its legacy alias ErrorException) generated inside an eval() block using a standard try-catch wrapper around the eval() call if the expression string itself does not contain the necessary logic to handle it.

However, there is a specific mechanism designed for this exact scenario: the error control operator @. This operator suppresses all errors triggered by the expression it precedes. While many developers dislike using @ because it hides critical bugs like undefined variable warnings, in the specific context of evaluating untrusted or dynamically generated mathematical expressions where runtime exceptions are expected side effects, it is a pragmatic tool.

Here is how you can structure the evaluation to handle division by zero gracefully:

$expression = "$foo + $bar / ($baz - $bak)";
$result = @eval("return " . $expression);

if ($result === false || !is_numeric($result)) {
    // Handle the case where an error occurred or the result is invalid
    $result = 0; 
}

In this approach, the @ operator attached to the eval() call tells PHP to ignore any E_WARNING, E_NOTICE, or E_ERROR that occurs during the execution of the string. Division by zero generates a DivisionByZeroError (in modern PHP) which is technically an error, not just a warning. By suppressing this, the script continues without crashing, and you can assign a default value to $result.

A common misconception is that you can catch the exception inside the eval() string using try-catch. While syntactically possible if the string contains valid PHP code, relying on eval to handle its own exceptions introduces significant complexity. The evaluated code runs in a separate scope, and ensuring that variables defined in the catch block (like $e) are accessible or correctly scoped can be error-prone. Furthermore, try-catch blocks inside eval strings require precise syntax that is easy to break if the dynamic expression logic changes slightly.

The trade-off here is explicit: you are trading visibility of errors for stability. If your application crashes on division by zero, it indicates a potential logical flaw in the data being parsed. However, if the mathematical domain allows for zero denominators as valid edge cases, suppressing the error and defaulting to zero (or another safe value) is a deliberate design choice.

If you require more granular control than simple suppression, consider parsing the expression using a dedicated math library like math_eval or converting the expression string into a format that avoids dynamic execution altogether. But if you are constrained to eval, the error control operator remains the standard pattern for handling inherent mathematical risks in dynamically generated code.

Our network