PHP try-catch 不起作用


PHP try-catch not working

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';   
}

但是,它不只是要捕获部分并返回nothing而是在以while开头的行中显示警告Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given。我从来没有想过在 php 中使用异常,但在 C# 中经常使用它们,似乎在 PHP 中它们的工作方式不同,或者一如既往,我错过了一些明显的东西。

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

但最好解决此问题,因为您可以防止它。

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

try {
    catch ('Exception $e) {
       //do something when exception is thrown
}
catch ('Error $e) {
  //do something when error is thrown
}

或更具包容性的解决方案

try {
catch ('Exception $e) {
   //do something when exception is thrown
}
catch ('Throwable $e) {
  //do something when Throwable is thrown
}

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

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

Welp,不幸的是,这是关于PHP的问题。try/catch 语句将捕获异常,但您收到的是一个老式的 PHP 错误。

您必须通过以下方式捕获这样的错误:http://php.net/manual/en/function.set-error-handler.php

要么这样做,要么在执行mysqli_fetch_array之前检查$matrix是否是mysqli_result对象。

PHP 正在生成警告,而不是异常。无法捕获警告。它们更像是 C# 中的编译器警告。