PHP錯誤處理方法總結_PHP教程

來源:互聯網
上載者:User
在php中錯誤處理的方法有很多,特別是到了php5之後還提供了專門的php處理類,下面我收藏了關於PHP錯誤處理一些方法與程式分享給大家。

在程式中直接判斷

基本的錯誤處理:使用 die() 函數
第一個例子展示了一個開啟文字檔的簡單指令碼:

代碼如下 複製代碼

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

如果檔案不存在,您會獲得類似這樣的錯誤:

Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:webfoldertest.php on line 2

更多詳細的

代碼如下 複製代碼


//開啟一個檔案 未做任何處理
//$fp =fopen("aa.txt","r");
//echo "OK";

//處理:判斷檔案是否存在 file_exists
/*
if(!file_exists("aa.txt")){
echo "檔案不存在";
//不存在就退出
exit(); //退出後,下面面的代碼就不執行了
}else{
$fp =fopen("aa.txt","r");
//...操作完之後 關閉
fclose($fp);

}

echo "OK";
*/
//PHP處理錯誤的3種方法

//第一種:使用簡單的die語句

/* if(!file_exists("aa.txt")){

die("檔案不存在。。。"); //不存在就直接退出
}else{
$fp =fopen("aa.txt","r");
//...操作完之後 關閉
fclose($fp);

}

echo "OK";
*/
//更簡單的方式
file_exists("aa.txt") or die("檔案不存在");


?>

第二種:錯誤處理器 錯誤層級 處理錯誤方式

代碼如下 複製代碼

//
/*
使用error_function(error_level,error_message,
error_file,error_line,error_context)
該函數必須有能力處理至少兩個參數 (error level 和 error message),
但是可以接受最多五個參數(可選的:file, line-number 以及 error context):

*/

//改寫set_error_handler方法
//如果出現 E_WARNING 這個錯誤就調用my_error 處理方法
set_error_handler("my_error",E_WARNING);
set_error_handler("my_error2",E_USER_ERROR);
//設定中國對應的時區
date_default_timezone_set('PRC');

function my_error($errno,$errmes){

echo "$errno"; //輸出錯誤報表層級
echo "錯誤資訊是:".$errmes;
exit();
}

function my_error2($errno,$errmes){

//echo "錯誤資訊是:".$errno,$errmes;
//exit();
//把錯誤資訊輸入到文本中儲存已備查看 使用到error_log()函數
$message ="錯誤資訊是:".$errno." ".$errmes;
error_log(date("Y-m-d G:i:s")."---".$message."rn",3,"myerror.txt"); // rn 表示換行
}

//開啟一個檔案 未做任何處理

//$fp =fopen("aa.txt","r");
//echo "OK";

//使用自訂錯誤 要添加觸發器 這個trigger_error()函數來指定調用自訂的錯誤
$age=200;
if($age>150){
//echo "年齡過大";
//調用觸發器 同時指定錯誤層級 這裡需要查看協助文檔
trigger_error("不好了出大問題了",E_USER_ERROR);
//exit();
}


?>

PHP 異常處理

PHP 5 提供了一種新的物件導向的錯誤處理方法


如果異常沒有被捕獲,而且又沒用使用 set_exception_handler() 作相應的處理的話,那麼將發生一個嚴重的錯誤(致命錯誤),並且輸出 "Uncaught Exception" (未捕獲異常)的錯誤訊息。

讓我們嘗試拋出一個異常,同時不去捕獲它:

代碼如下 複製代碼

//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception
checkNum(2);
?>

上面的代碼會獲得類似這樣的一個錯誤:

Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:webfoldertest.php:6
Stack trace: #0 C:webfoldertest.php(12):
checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6Try, throw 和 catch
要避免上面例子出現的錯誤,我們需要建立適當的代碼來處理異常。

處理處理常式應當包括:

1.Try - 使用異常的函數應該位於 "try" 代碼塊內。如果沒有觸發異常,則代碼將照常繼續執行。但是如果異常被觸發,會拋出一個異常。
2.Throw - 這裡規定如何觸發異常。每一個 "throw" 必須對應至少一個 "catch"
3.Catch - "catch" 代碼塊會捕獲異常,並建立一個包含異常資訊的對象
讓我們觸發一個異常:

代碼如下 複製代碼

//建立可拋出一個異常的函數
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

//在 "try" 代碼塊中觸發異常
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}

//捕獲異常
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>

上面代碼將獲得類似這樣一個錯誤:

Message: Value must be 1 or below

建立一個自訂的 Exception 類
建立自訂的例外處理常式非常簡單。我們簡單地建立了一個專門的類,當 PHP 中發生異常時,可調用其函數。該類必須是 exception 類的一個擴充。

這個自訂的 exception 類繼承了 PHP 的 exception 類的所有屬性,您可向其添加自訂的函數。

我們開始建立 exception 類:

代碼如下 複製代碼

class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': '.$this->getMessage().' is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example...com";

try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
}

catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>

這個新的類是舊的 exception 類的副本,外加 errorMessage() 函數。正因為它是舊類的副本,因此它從舊類繼承了屬性和方法,我們可以使用 exception 類的方法,比如 getLine() 、 getFile() 以及 getMessage()。


http://www.bkjia.com/PHPjc/444611.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/444611.htmlTechArticle在php中錯誤處理的方法有很多,特別是到了php5之後還提供了專門的php處理類,下面我收藏了關於PHP錯誤處理一些方法與程式分享給大家。...

  • 聯繫我們

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