PHP try/catch 块中未捕获除零警告
我有这个 PHP 代码。每当 y 变为零时,它就会显示警告而不是捕获异常。我的代码有什么问题吗?
try
{
return($x % $y);
throw new Exception("Divide error..");
}
catch(Exception $e){
echo "Exception:".$e->getMessage();
}
我收到此警告:
Warning: Division by zero in file.php
catch 块未运行。我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
警告也不例外。异常处理技术无法捕获警告。您自己的异常永远不会抛出,因为您之前总是
返回
。您可以使用
@
运算符(如@($x % $y)
)抑制警告,但您真正应该做的是确保$y
不会变成0。即:
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.:
是的,您正在
抛出
之前执行return
。因此,永远不会执行throw
,并且不会抛出或捕获任何异常。Yes, you are executing the
return
before thethrow
. Hence thethrow
is never executed and no exception is thrown nor caught.这是应该如何完成
但是因为如果您想隐藏错误并单独处理它,您会收到警告
您现在可以使用
@
符号,您可以测试该值并查看它是否具有它所具有的值
this is how it should be done
But since you are getting a warning if you want to hide the error and handle it discretely
You can use the
@
signnow you can test the value and see if it has the value it has