How to catch a division by zero?
- by Cristian Castiblanco
I have a large mathematical expression that has to be created dinamically. So, 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?