php異常處理 錯誤處理

來源:互聯網
上載者:User

標籤:http   使用   os   io   strong   檔案   資料   ar   

1.   什麼是異常?

異常是程式運行中由外部環境引起的意外情況,使程式無法按照正常流程執行下去。

2.   PHP異常處理機制

在 PHP 代碼中所產生的異常可被 throw 語句拋出並被 catch 語句捕獲。需要進行異常處理的代碼都必須放入 try 代碼塊內,以便捕獲可能存在的異常。每一個 try 至少要有一個與之對應的 catch。

try{

            //可能出現錯誤或異常的代碼

                    } catch(Exception $e){

 

            //對異常處理,方法:

                //1、自己處理

                //2、不處理,將其再次拋出

        }

捕獲後對異常的處理:1對於定時多次執行的程式可將異常資訊儲存到資料庫裡。

2調試階段可以輸出堆棧資訊以便快速發現問題,

try {

                            throw new Exception(‘a Exception‘);

                     } catch (Exception $e) {

                            echo "MESSAGE = " . $e->getMessage() . "\n" . "STACK TRACE = \n" . $e->getTraceAsString()  ;

                                                                                

                     }

 

3發布後輸出異常資訊即可。

try {

                            throw new Exception(‘a Exception‘);

                     } catch (Exception $e) {

                            echo "MESSAGE = " . $e->getMessage()  ;                                                                               

                     }

 

 

使用多個 catch 可以捕獲不同的類所產生的異常。

<?php

class customException extends Exception {

       public function errorMessage() {

              $errorMsg = ‘Error on line ‘ . $this->getLine () . ‘ in ‘ . $this->getFile () . ‘: <b>‘ . $this->getMessage () . ‘</b> is not a valid E-Mail address‘;

              return $errorMsg;

       }

}

$email = "[email protected]";

try {

       if (filter_var ( $email, FILTER_VALIDATE_EMAIL ) === FALSE) {

              throw new customException ( $email );

       }

       if (strpos ( $email, "example" ) !== FALSE) {

              throw new Exception ( "$email is an example e-mail" );

       }

} catch ( customException $e ) {

       echo $e->errorMessage ();

}

catch ( Exception $e ) {

       echo $e->getMessage ();

}

?>

 

當 try 代碼塊不再拋出異常或者找不到 catch 能匹配所拋出的異常時,PHP 代碼就會在跳轉到最後一個 catch 的後面繼續執行。當然,PHP 允許在 catch 代碼塊內再次拋出(throw)異常。當一個異常被拋出時,拋出異常時所在的代碼塊後邊的代碼將不會繼續執行,而 PHP 就會嘗試尋找第一個能與之匹配的 catch。

如果一個異常沒有被捕獲,可以使用 set_exception_handler() 作相應的處理,必須在異常拋出前定義一個異常處理函數$exception_handler,並用

set_exception_handler($exception_handler) 設定為預設異常處理器,用於沒有用 try/catch 塊來捕獲的異常。例子:

<?php

function exception_handler($exception) {

  echo "Uncaught exception: " , $exception->getMessage(), "\n";

}

 

set_exception_handler(‘exception_handler‘);

 

throw new Exception(‘An Exception‘);

 

?>

 

以上程式輸出為:Uncaught exception: An Exception

如果異常沒有被捕獲並且沒有使用set_exception_handler()作相應的處理

那麼 PHP 將會產生一個嚴重的錯誤,並且輸出 Uncaught Exception ... (未捕獲異常)的提示資訊。

如下:

<?php

throw new Exception(‘An Exception‘);

?>

以上程式輸出:Fatal error: Uncaught exception ‘Exception‘ with message ‘An Exception‘ in D:\xampp\htdocs\woo\exception\1.php:2 Stack trace: #0 {main} thrown in D:\xampp\htdocs\woo\exception\1.php on line 2

 

3.Zendframework如何處理異常

Zend_Controller_Front 預設將捕捉所有異常並註冊到響應對象,響應對象預設不會顯示異常訊息。

預設地,錯誤處理器外掛程式(error handler plugin) 將會被註冊並啟用。它作為一個postDispatch()外掛程式,檢查分發器、動作控制器或者其他的異常是否發生。異常的抓取被記錄在一個對象裡,這個對象註冊在請求裡。使用Zend_Controller_Action::_getParam(‘error_handler‘)來讀取它.如果發生異常,它將轉向一個錯誤處理控制器ErrorController::errorAction()。異常由錯誤管理器通過抓取error_handler對象的exception屬性來觸發的。

public function errorAction()

{

//擷取error_handler對象

        $errors = $this->_getParam(‘error_handler‘);

        switch ($errors->type) {

            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:

            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

               $this->getResponse()->setHttpResponseCode(404);

                    break;               

             default:

                    // application error

                    $this->getResponse()->setHttpResponseCode(500);

                    break;               

        }

//擷取異常

$exception = $errors->exception;

對異常處理根據不同情況傳給view輸出或者儲存到資料庫裡。

}

 

4.PHP錯誤處理機制

在 PHP 中,預設的錯誤處理很簡單。一條訊息會被發送到瀏覽器,這條訊息帶有檔案名稱、行號以及一條描述錯誤的訊息。

例如

<?php

$file=fopen("welcome.txt","r");

?>

結果是:Warning: fopen(welcome.txt): failed to open stream: No such file or directory in D:\xampp\htdocs\woo\error\2.php on line 2

 

基本的錯誤處理:使用 die() 函數

<?php

if(!file_exists("welcome.txt"))

 {

 die("File not found");

 }

else

 {

 $file=fopen("welcome.txt","r");

 }

?>

在錯誤之後終止了指令碼並輸出自訂資訊。

 

建立自訂錯誤處理器

 

先建立一個處理錯誤的函數,該函數必須有能力處理至少兩個參數 (error level 和 error message),但是可以接受最多五個參數(可選的:file, line-number 以及 error context)

function errorHandler($errNo,$errMsg){

       echo "<b>Error:</b> [$errNo] $errMsg<br />";

       echo "Ending Script";

       die();

}

用set_error_handler設定errorHandler為錯誤處理函數。

<?php

function errorHandler($errNo,$errMsg){

       echo "<b>Error:</b> [$errNo] $errMsg<br />";

       echo "Ending Script";

       die();

}

set_error_handler("errorHandler");

 

$test=2;

if ($test>1)

 {

//觸發錯誤

 trigger_error("Value must be 1 or below",E_USER_WARNING);

 }

?>

輸出:Error: [512] Value must be 1 or below

Ending Script

 

也可以在錯誤處理函數中將錯誤資訊託管至ErrorException,再處理。

 

function errorExceptionHandler($errNo, $errMsg, $errFile, $errLine)

{

       if (in_array($errNo, array(E_USER_ERROR, E_ERROR))) {

              throw new ErrorException($errMsg, 0, $errNo, $errFile, $errLine);

       }

       return false;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.