除以零警告不会在PHP try/catch块中捕获

ins*_*iac 0 php exception try-catch

我有这个PHP代码.每当y变为零时,它会显示警告而不是捕获异常.我的代码有什么问题吗?

try
{
    return($x % $y); 
    throw new Exception("Divide error..");
}
catch(Exception $e){
    echo "Exception:".$e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)

我收到了这个警告:

Warning: Division by zero in file.php
Run Code Online (Sandbox Code Playgroud)

catch块未运行.我究竟做错了什么?

dec*_*eze 7

警告也不例外.使用异常处理技术无法捕获警告.从来没有抛出你自己的异常return.

您可以使用@操作符来抑制警告@($x % $y),但您应该做的是确保$y不会变为0.

即:

if (!$y) {
    return 0; // or null, or do something else
} else {
    return $x % $y;
}
Run Code Online (Sandbox Code Playgroud)