簡體   English   中英

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而是顯示警告Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given在以while開頭的行中Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given 我從來沒有在php中使用異常,但在C#中使用它們很多,而且在PHP中看起來它們的工作方式不同,或者像往常一樣,我遺漏了一些明顯的東西。

您無法使用try-catch塊處理警告/錯誤,因為它們不是例外。 如果要處理警告/錯誤,則必須使用set_error_handler注冊自己的錯誤處理程序。

但最好解決這個問題,因為你可以阻止它。

在PHP中,警告不是例外。 通常,最好的做法是使用防御性編碼來確保結果符合您的預期。

Welp,遺憾的是這是關於PHP的問題。 Try / catch語句將捕獲異常,但您收到的是一個老派的PHP錯誤。

你必須得到這樣的錯誤: http//php.net/manual/en/function.set-error-handler.php

或者在執行mysqli_fetch_array之前檢查$ matrix是否是mysqli_result對象。

異常只是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
}

BTW:Java有類似的行為。

PHP正在生成警告,而不是例外。 警告無法捕獲。 它們更像是C#中的編譯器警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM