什麼是 PHP 中的異常處理?
異常是在程式執行期間出現的問題。在程式執行過程中,當發生異常時,語句後面的程式碼將不會執行,PHP 將嘗試查詢第一個匹配的 catch 塊。如果未捕獲異常,則會發出帶有“未捕獲異常”的 PHP 致命錯誤。
語法
try { print "this is our try block"; throw new Exception(); }catch (Exception $e) { print "something went wrong, caught yah! n"; }finally { print "this part is always executed"; }
示例
<?php function printdata($data) { try { //If var is six then only if will be executed if($data == 6) { // If var is zero then only exception is thrown throw new Exception('Number is six.'); echo "
After throw (It will never be executed)"; } } // When Exception has been thrown by try block catch(Exception $e){ echo "
Exception Caught", $e->getMessage(); } //this block code will always executed. finally{ echo "
Final block will be always executed"; } } // Exception will not be rised here printdata(0); // Exception will be rised printdata(6); ?>
輸出
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
備註
要處理異常,程式程式碼必須在 try 塊內。每個 try 必須至少有一個相應的 catch 塊。可以使用多個 catch 塊來捕獲不同類的異常。
廣告