Divide by Zero warning is not caught in a PHP try/catch block [duplicate]
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;
}
Yes, you are executing the return
before the throw
. Hence the throw
is never executed and no exception is thrown nor caught.
this is how it should be done
$value;
try
{
$value = $x%$y;
}
catch(Exception $e){
throw new Exception("Divide error..");
echo "Exception:".$e->getMessage();
}
return $value
But since you are getting a warning if you want to hide the error and handle it discretely
You can use the @
sign
$value = @$x%$y;
now you can test the value and see if it has the value it has
精彩评论