PHP try-catch 不起作用

2022-08-30 14:08:21
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';   
}

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


答案 1

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

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


答案 2

异常只是 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也有类似的行为。


推荐