自定義異常 例子

以下4段代碼爲我在waylife項目中的簡單應用(非生產環境),不健壯也不美化,但該SNS項目早已經夭折。

1、異常類的層級關係:

  1. class NotFoundException extends Exception{}  
  2. class InputException extends Exception{}  
  3. class DBException extends Exception{} 


2、配置未捕捉異常的處理器:

  1. function exception_uncaught_handler(Exception $e) {  
  2. header('Content-type:text/html; charset=utf-8');  
  3. if ($e instanceof NotFoundException)  
  4. exit($e->getMessage());  
  5. elseif ($e instanceof DBException)  
  6. exit($e->getMessage());  
  7. else  
  8. exit($e->getMessage());  
  9. }  
  10. set_exception_handler('exception_uncaught_handler');  

3、在數據庫連接代碼,手動拋出DBException異常但未使用try…catch進行捕獲處理,該異常將被PHP自定義異常處理器exception_uncaught_handler()函數處理:

  1. $this->resConn = mysql_connect ($CONFIGS['db_host'], $CONFIGS['db_user'], $CONFIGS['db_pwd']);  
  2. if (false == is_resource($this->resConn))  
  3. throw new DBException('數據庫連接失敗。'.mysql_error($this->resConn)); 


4、業務邏輯一瞥:

  1. if (0 != strcmp($curAlbum->interest_id, $it))  
  2. throw new NotFoundException('很抱歉,你所訪問的相冊不存在');  

以上就是PHP自定義異常處理器的具體使用方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章