PHP try-catch无法正常工作

And*_*ius 18 php exception try-catch

try     
{
    $matrix = Query::take("SELECT moo"); //this makes 0 sense

    while($row = mysqli_fetch_array($matrix, MYSQL_BOTH)) //and thus this line should be an error
    {

    }

    return 'something';
}
catch(Exception $e)
{
    return 'nothing';   
}
Run Code Online (Sandbox Code Playgroud)

然而,而不是只是去捕捉部分并返回nothing它显示Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given在行开始时的警告while.我从来没有在php中使用异常,但在C#中使用它们很多,而且在PHP中看起来它们的工作方式不同,或者像往常一样,我遗漏了一些明显的东西.

Phi*_*ipp 31

您无法使用try-catch块处理警告/错误,因为它们不是例外.如果要处理警告/错误,则必须注册自己的错误处理程序set_error_handler.

但最好解决这个问题,因为你可以阻止它.


dat*_*age 6

在PHP中,警告不是例外.通常,最好的做法是使用防御性编码来确保结果符合您的预期.


Gil*_*ram 5

异常只是Throwable的子类。要捕获错误,您可以尝试执行以下操作之一:

try {

    catch (\Exception $e) {
       //do something when exception is thrown
}
catch (\Error $e) {
  //do something when error is thrown
}
Run Code Online (Sandbox Code Playgroud)

或更广泛的解决方案

try {

catch (\Exception $e) {
   //do something when exception is thrown
}
catch (\Throwable $e) {
  //do something when Throwable is thrown
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句:Java具有类似的行为。

  • 我使用 `\Exception` 而不是 `Exception` 并且它有效。您能详细说明一下“Exception”之前的 \(斜杠)在这里有何巨大的不同吗? (3认同)
  • @Shashanth 使用不带斜杠的“Exception”假设您在顶部有一个“use Exception;”语句,或者没有使用命名空间,“\”使其在全局 PHP 命名空间中查找,因此它会捕获PHP `Exception` 以及基于它的任何类 - 官方文档:https://php.net/manual/en/class.exception.php (3认同)