PHP自訂異常處理器的幾種使用方法_PHP教程

來源:互聯網
上載者:User
處理異常在

以下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自訂異常處理器的具體使用方法。


http://www.bkjia.com/PHPjc/446148.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446148.htmlTechArticle處理異常在 以下4段代碼為我在waylife項目中的簡單應用(非生產環境),不健壯也不美化,但該SNS項目早已經夭折。 1、異常類的層級關係...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.