I have a large mathematical expression that has to be created dynamically. For example, once I have parsed "something" the result will be a string like: "$foo+$bar/$baz";
.
So, for calculating the result of that expression I'm using the eval
function... something like this:
eval("\$result = $expresion;");
echo "The result is: $result";
The problem here is that sometimes I get errors that says there was a division by zero, and I don't know how to catch that Exception. I have tried things like:
eval("try{\$result = $expresion;}catch(Exception \$e){\$result = 0;}");
echo "The result is: $result";
Or:
try{
eval("\$result = $expresion;");
}
catch(Exception $e){
$result = 0;
}
echo "The result is: $result";
But it does not work. So, how can I avoid that my application crashes when there is a division by zero?
Edit:
First, I want to clarify something: the expression is built dynamically, so I can't just eval if the denominator is zero. So... with regards to the Mark Baker's comment, let me give you an example. My parser could build something like this:
"$foo + $bar * ( $baz / ( $foz - $bak ) )"
The parser build the string step by step without worrying about the value of the vars... so in this case if $foz == $bak
there's in fact a division by zero: $baz / ( 0 )
.
On the other hand as Pete suggested, I tried:
<?php
$a = 5;
$b = 0;
if(@eval(" try{ \$res = $a/$b; } catch(Exception \$e){}") === FALSE)
$res = 0;
echo "$res\n";
?>
But it does not print anything.
As others have mentioned, consider trying a solution that will let you check if the denominator is 0.
Since that advice seems useless your purpose, here's a little background on PHP error handling.
Early versions of PHP didn't have exceptions. Instead, error messages of various levels were raised (Notices, Warnings, Etc). A Fatal error stops execution.
PHP5 brought exceptions to the table, and newer PHP provided libraries (PDO) will throw exceptions when bad/unexpected things happen. Hoever, the core codebase was NOT rewritten to use exception. Core functions and operations still rely on the old error system.
When you divide by 0, you get a Warning, not an exception
If you want to "catch" these, you'll need to set a custom error handler that will detect division by zero errors and do something about them. Unfortunately, custom error handlers are a catch all, which means you'll also need to write some code to do something appropriate with all other errors.