異常是程式執行過程中出現的問題。在程式執行過程中,發生異常時,該語句後面的程式碼將不會被執行,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 "</p><p> After throw (It will never be executed)"; } } // When Exception has been thrown by try block catch(Exception $e){ echo "</p><p> Exception Caught", $e->getMessage(); } //this block code will always executed. finally{ echo "</p><p> 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 區塊內。每次嘗試必須至少有一個相應的 catch 區塊。多個catch區塊可用於擷取不同類別的異常。
以上是PHP中的異常處理是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!