PHP學習筆記7:錯誤和異常處理

讀《PHP和MySQL Web開發》筆記合集: php

http://my.oschina.net/bluefly/blog/478580 web

一、異常處理概念 app

1)異常處理在 try 代碼塊被調用執行
try
{
    //code goes here
}
2)PHP中,異常必須手動拋出
throw new Exception('message',code);
這是一個語言結構,而不是一個函數。
能夠在throw子句中傳遞任何其餘對象

3)在try代碼塊以後,必須至少給出一個catch代碼塊。
catch ( typehint exception)
{
  //  handle exception
}
能夠將多個catch 代碼塊與一個try 代碼塊進行關聯。
例子:
<?php

try  {
  throw new Exception("A terrible error has occurred", 42);
}
catch (Exception $e) {
  echo "Exception ". $e->getCode(). ": ". $e->getMessage()."<br />".
  " in ". $e->getFile(). " on line ". $e->getLine(). "<br />";
}

?>


二、Exception類 函數

Exception

(PHP 5 >= 5.1.0) this

簡介

Exception是全部異常的基類。 編碼

類摘要

Exception {
/* 屬性 */
protectedstring $message ;
protectedint $code ;
protectedstring $file ;
protectedint $line ;
/* 方法 */
public __construct ([ string $message = "" [, int $code = 0 [,  Exception$previous =  NULL ]]] )
final public string  getMessage ( void )
final public Exception  getPrevious ( void )
final public int  getCode ( void )
final public string  getFile ( void )
final public int  getLine ( void )
final public array  getTrace ( void )
final public string  getTraceAsString ( void )
public string __toString ( void )
final private void  __clone ( void )
}

屬性

message

異常消息內容 spa

code

異常代碼 .net

file

拋出異常的文件名 code

line

拋出異常在該文件中的行號 對象

Table of Contents

三、用戶自定義異常
用戶能夠擴展Exception類來建立本身的異常類。
注意,Exception類大多數公有方法都是final,不能重載,咱們能夠建立本身的Exception子類,可是不能改變這些基本方法的行爲。可是注意,__toString()函數能夠重載。
例子:
<?php

class myException extends Exception
{
  function __toString()
  {
       return "<table border=\"1\">
       <tr>
       <td><strong>Exception ".$this->getCode()."
       </strong>: ".$this->getMessage()."<br />"."
       in ".$this->getFile()." on line ".$this->getLine()."
       </td>
       </tr>
       </table><br />";
   }
}

try
{
  throw new myException("A terrible error has occurred", 42);
}
catch (myException $m)
{
   echo $m;
}

?>

四、I/O部分與建議
I/O部分容易出異常,一般,良好的編碼習慣要求try代碼塊的代碼量較少,而且在代碼塊的結束處捕獲相關異常。
注意:若是一場沒有匹配的catch語句塊,PHP將報告一個致命錯誤。
例子:
// open file for appending
try
{
  if (!($fp =  @fopen("$DOCUMENT_ROOT/../orders/orders.txt", 'ab')))
       throw new fileOpenException();

  if (!flock($fp, LOCK_EX))
      throw new fileLockException();

  if (!fwrite($fp, $outputstring, strlen($outputstring)))
      throw new fileWriteException();
  flock($fp, LOCK_UN);
  fclose($fp);
  echo "<p>Order written.</p>";
}
catch (fileOpenException $foe)
{
   echo "<p><strong>Orders file could not be opened.
         Please contact our webmaster for help.</strong></p>";
}
catch (Exception $e)
{
   echo "<p><strong>Your order could not be processed at this time.
         Please try again later.</strong></p>";
}

五、異常與PHP其餘錯誤處理機制
PHP還提供了複雜的錯誤處理機制,注意,好比異常處理和@錯誤抑制並不會影響。
例子:
 if (!($fp =  @fopen("$DOCUMENT_ROOT/../orders/orders.txt", 'ab')))
       throw new fileOpenException();
若是該函數調用失敗,PHP將發出一個浸膏,根據php.ini的設置進行錯誤報告或記錄。
相關文章
相關標籤/搜索