# 7. 錯誤與例外處理 {%hackmd QnyEFBdERZebn4iQDXNPnA %} ## 本章重點:了解PHP出錯後,如何處理?(即如何偵查故障排錯)(出錯=例外) ## 01 例外處理概念 - 使用try, catch ```php= try{ //嘗試某件可能會出錯的事 //do something, like throwing exceptions throw new Exception($message, $code); //throw 會觸發例外處理機制 } catch (Exception $e){ //catch用來處理例外 } finally { //無論是否有例外產生,必定執行 echo 'Always runs!'; } ``` ## 02 Exception 類別 - 是一個PHP內建的類別 - 可接收三個參數 - 錯誤訊息 - 錯誤代碼 - 之前的例外 - 內建方法 - getCode() - 回傳代碼 - getMessage() - 回傳訊息 - getFile() - 回傳完整路徑 - getLine() - 回傳發出例外的行數 - getTrace() - 回傳陣列,裡面有例外的回溯 - getTraceAsString() - 與上面相同,但回傳字串 - getPrevious() - 回傳上一個例外(即Exception的第三個參數) - __toString() - 提供以上所有方法所提供的資訊 ## 03 自訂例外 - 擴充Exception類別(參考P.214) ```php= //自訂義例外處理類別,繼承自Exception class myException extends Exception{ function __toString(){ //可覆寫 return "<strong>Exception ".$this->getCode()."</strong>: ".$this->getMessage()."<br />"."in ".$this->getFile()." on line ".$this->getLine()."<br />"; } } try { throw new myException("A terrible wrror has ocurred", 42); } catch (myException $m){ echo $m; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up