PHP, How to catch a division by zero?
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 "$resn";
?>
But it does not print anything.
if ($baz == 0.0) {
echo 'Divisor is 0';
} else {
...
}
而不是使用eval,如果您在evalled表达式中使用用户输入,这是非常危险的,为什么不在PHPClasses上使用适当的解析器(如evalmath),并在除以零时引发干净的异常
Here's another solution:
<?php
function e($errno, $errstr, $errfile, $errline) {
print "caught!n";
}
set_error_handler('e');
eval('echo 1/0;');
See set_error_handler()
您只需设置一个错误处理程序即可在发生错误时引发异常:
set_error_handler(function () {
throw new Exception('Ach!');
});
try {
$result = 4 / 0;
} catch( Exception $e ){
echo "Divide by zero, I don't fear you!".PHP_EOL;
$result = 0;
}
restore_error_handler();
链接地址: http://www.djcxy.com/p/11902.html
下一篇: PHP,如何通过零来捕获一个分区?