2012-06-26 101 views
17

我試圖弄清楚PHP中的throw new Exception後面的代碼是否仍然執行 - 我已經嘗試過了,它似乎沒有輸出任何內容,但是很想知道。'拋出新的異常'需要退出()?

+0

我不知道什麼是異常的一點,如果它不會導致堆棧展開(直到適當的條件,例如'catch',阻止它展開堆棧)... – 2012-06-26 19:50:12

+8

_When exception is拋出後,語句後面的代碼將不會執行,並且PHP將嘗試查找第一個匹配的catch塊。如果沒有捕獲到異常,除非使用set_exception_handler()._ [來自文檔](http:// php。)定義了一個處理程序,否則將發出一個PHP致命錯誤,並帶有「Uncaught Exception ...」消息。淨/手動/ EN/language.exceptions.php) –

回答

32

不,不執行拋出異常後的代碼。

在此代碼示例我用數字標記,其將被執行的行(碼流):

try { 
    throw new Exception("caught for demonstration");     // 1 
    // code below inside the try{} block is never executed 
    echo "you won't read this." . PHP_EOL; 
} catch (Exception $e) { 
    // you may want to react on the Exception here 
    echo "exception caught!" . PHP_EOL;         // 2 
}  
// execution flow continues here, because Exception above has been caught 
echo "yay, lets continue!" . PHP_EOL;         // 3 
throw new Exception("uncaught for demonstration");      // 4, end 

// execution flow never reaches this point because of the Exception thrown above 
// results in "Fatal Error: uncaught Exception ..." 
echo "you won't see me, too" . PHP_EOL; 

參見PHP manual on exceptions

當一個異常被拋出後的語句,代碼將不會被執行,並且PHP將嘗試查找第一個匹配的catch塊。如果未捕獲到異常,除非已使用set_exception_handler()定義了處理程序,否則會發出PHP致命錯誤,並顯示「Uncaught Exception ...」消息。

3

不,不會執行throw語句後的代碼。很像return