異常處理:意外,是在程序運行過程中發生的意料之外的事,使用異常改變腳本正常流程。
try
{
}
catch(異常對象)
{
}
注意:提示發生了什麼異常,不是我們主要做的事情,需要在catch中解決這個異常,如果解決不了,則拋出給用戶。
<?php
class OpenFileException extends Exception{
function open(){
touch("tmp.txt");
$file=fopen("tmp.txt","r");
return $file;
}
}
class DemoException extends Exception{
function pro(){
echo "Demo異常<br />";
}
}
class MyClass{
function openfile(){
$file=@fopen("aaa.txt","r");
if(!$file)
throw new OpenFileException("文件打開失敗");
}
function demo($num=0){
if($num==1)
throw new DemoException("演示異常!");
}
}
try{
$my=new MyClass();
$my->openfile();
$my->demo("1");
}catch(OpenFileException $e){
echo $e->getMessage()."<br />";
$file=$e->open();
}catch(DemoException $e){
echo $e->getMessage()."<br />";
$e->pro();
}catch(Exception $e){ //接收拋出了但沒有處理的所有異常
echo $e->getMessage();
}
?>
錯誤處理:1.語法錯誤 2.運行時的錯誤 3.邏輯錯誤
錯誤報告: 錯誤:E_ERROR 警告:E_WARNING 注意:E_NOTICE
建議: 開發階段:開發是輸出所有的錯誤報告,有利於調試程序。運行階段:不要讓程序輸出任何一種錯誤報告。
<?PHP
error_reporting(E_ALL); //1.指定錯誤報告,錯誤類型為全部
//ini_set("error_reporting",E_ALL); //臨時改變配置文件的值
//ini_get("upload_max_filesize"); //獲取配置文件的值
ini_set("display_errors","off"); //2.關閉配置文件中的顯示錯誤
ini_set("log_errors","on"); //3.開啟錯誤日志功能
ini_set("error_log","C:/error.log"); //4.指定錯誤文件(可寫)
error_log("this is a error message!!!!"); //輸出錯誤信息
?>