除以零警告不会被抓到一个PHP try / catch块 [英] Divide by Zero warning is not caught in a PHP try/catch block
本文介绍了除以零警告不会被抓到一个PHP try / catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
y
变为零时,它会显示一个警告,而不是捕获异常。我的代码有什么问题吗? try
{
return($ x%$ y) ;
throw new Exception(Divide error ..);
}
catch(Exception $ e){
echoException:。$ e-> getMessage();
}
我收到此警告:
警告:file.php中的零除以
解决方案
警告并不是例外。无法使用异常处理技术捕获警告。你自己的例外永远不会被抛出,因为你总是返回
。
你可以使用 @
运算符像 @($ x%$ y)
,但你应该做的是确保 $ y
不成为0。
即:
if(!$ y){
return 0; //或null,或做其他事情
} else {
return $ x%$ y;
}
I have this PHP code. Whenever y
becomes zero, it shows a warning instead of catching the exception. Is there anything wrong with my code?
try
{
return($x % $y);
throw new Exception("Divide error..");
}
catch(Exception $e){
echo "Exception:".$e->getMessage();
}
I got this warning:
Warning: Division by zero in file.php
The catch block is not run. What am I doing wrong?
解决方案
A warning is not an exception. Warnings cannot be caught with exception handling techniques. Your own exception is never thrown since you always return
before.
You can suppress warnings using the @
operator like @($x % $y)
, but what you should really do is make sure $y
does not become 0.
I.e.:
if (!$y) {
return 0; // or null, or do something else
} else {
return $x % $y;
}
这篇关于除以零警告不会被抓到一个PHP try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文