2017-05-25 106 views
1

我是新來的PHP,我來自java的背景,我想知道爲什麼php不會直接在try塊中發生異常而沒有手動拋出異常。 例如爲什麼不進入catch塊而沒有拋出異常

<?php 
//create function with an exception 
function checkNum($number) { 
    if($number/0) { 
    throw new Exception("Value must be 1 or below"); 
    } 
    return true; 
} 

//trigger exception in a "try" block 
try { 
    checkNum(2); 
    //If the exception is thrown, this text will not be shown 
    echo 'If you see this, the number is 1 or below'; 
} 

//catch exception 
catch(Exception $e) { 
    echo 'Message: ' .$e->getMessage(); 
} 
?> 

在上面的例子中,如果條件零異常的鴻溝正在發生,然後它會直接進入catch塊,而不是它進入裏面if.why?

+2

PHP的內置錯誤檢查不會引發異常。 – Barmar

+0

但我的問題是,是的,我想抓住它,但我不想執行,如果阻塞,如果異常是我在檢查除法的行,如果我刪除內部的扔,如果然後它不會去抓塊它會執行下一個代碼,在if語句中仍然有例外。 – pravin

+1

它不執行'if()'塊。 '$ number/0'由於除以0而返回'false',所以它不執行'if()'。然後函數返回'true',並打印'如果你看到這個'消息。 – Barmar

回答

2

您發佈的代碼不會做你說的那樣。

當你執行:

if ($number/0) 

除以零打印警告,然後返回false。由於該值不是真的,它不會進入if塊,因此它不會執行throw語句。該函數然後返回true。由於沒有拋出異常,執行調用checkNum(2)後的語句,因此它會打印該消息。

當我運行代碼,我得到的輸出:

Warning: Division by zero in scriptname.php on line 5 
If you see this, the number is 1 or below 

PHP不使用其內置的錯誤檢查異常。它只是顯示或記錄錯誤,如果它是一個致命錯誤,它會停止腳本。

雖然這已在PHP 7中進行了更改。它現在通過拋出Error類型的異常來報告錯誤。這不是Exception的子類,所以如果您使用catch (Exception $e)則不會被捕獲,因此您需要使用catch (Error $e)。見Errors in PHP 7。所以在PHP 7中,你可以寫:

<?php 
//create function with an exception 
function checkNum($number) { 
    if($number/0) { 
    throw new Exception("Value must be 1 or below"); 
    } 
    return true; 
} 

//trigger exception in a "try" block 
try { 
    checkNum(2); 
    //If the exception is thrown, this text will not be shown 
    echo 'If you see this, the number is 1 or below'; 
} 

//catch exception 
catch(Error $e) { 
    echo 'Message: ' .$e->getMessage(); 
} 
相關問題