PHP自定義異常處理器的幾種使用方法
處理異常在PHP編程中是經(jīng)常要被用到的。我們介紹的這個(gè)PHP自定義異常處理器為PHP內(nèi)置的exception_uncaught_handler()函數(shù)。該函數(shù)可用于設(shè)置用戶自定義的異常處理函數(shù),處理try…catch塊未捕獲的異常。#t#
以下4段代碼為我在waylife項(xiàng)目中的簡(jiǎn)單應(yīng)用(非生產(chǎn)環(huán)境),不健壯也不美化,但該SNS項(xiàng)目早已經(jīng)夭折。
1、異常類(lèi)的層級(jí)關(guān)系:
- class NotFoundException extends Exception{}
- class InputException extends Exception{}
- class DBException extends Exception{}
2、配置未捕捉異常的處理器:
- function exception_uncaught_handler(Exception $e) {
- header('Content-type:text/html; charset=utf-8');
- if ($e instanceof NotFoundException)
- exit($e->getMessage());
- elseif ($e instanceof DBException)
- exit($e->getMessage());
- else
- exit($e->getMessage());
- }
- set_exception_handler('exception_uncaught_handler');
3、在數(shù)據(jù)庫(kù)連接代碼,手動(dòng)拋出DBException異常但未使用try…catch進(jìn)行捕獲處理,該異常將被PHP自定義異常處理器exception_uncaught_handler()函數(shù)處理:
- $this->resConn = mysql_connect ($CONFIGS['db_host'], $CONFIGS['db_user'], $CONFIGS['db_pwd']);
- if (false == is_resource($this->resConn))
- throw new DBException('數(shù)據(jù)庫(kù)連接失敗。'.mysql_error($this->resConn));
4、業(yè)務(wù)邏輯一瞥:
- if (0 != strcmp($curAlbum->interest_id, $it))
- throw new NotFoundException('很抱歉,你所訪問(wèn)的相冊(cè)不存在');
以上就是PHP自定義異常處理器的具體使用方法。