Try- 使用異常的函數應該位於 "try"代碼塊內。若是沒有觸發異常,則代碼將照常繼續執行。可是若是異常被觸發,會拋出一個異常。php
Throw - 這裏規定如何觸發異常。每個 "throw" 必須對應至少一個 "catch"ide
Catch - "catch" 代碼塊會捕獲異常,並建立一個包含異常信息的對象 函數
讓咱們觸發一個異常:this
1 <?php 2//建立可拋出一個異常的函數 3function checkNum($number){ 4if($number>1){ 5thrownewException("Value must be 1 or below"); 6 } 7returntrue; 8} 910//在 "try" 代碼塊中觸發異常11try{12 checkNum(2);13//若是異常被拋出,那麼下面一行代碼將不會被輸出14echo 'If you see this, the number is 1 or below';15 }catch(Exception$e){16//捕獲異常17echo 'Message: ' .$e->getMessage();18}19 ?>
上面代碼將得到相似這樣一個錯誤:spa
Message: Value must be 1 or below
上面的代碼拋出了一個異常,並捕獲了它:code
建立 checkNum() 函數。它檢測數字是否大於 1。若是是,則拋出一個異常。 orm
在 "try" 代碼塊中調用 checkNum() 函數。 對象
checkNum() 函數中的異常被拋出 blog
"catch" 代碼塊接收到該異常,並建立一個包含異常信息的對象 ($e)。 ci
經過從這個 exception 對象調用 $e->getMessage(),輸出來自該異常的錯誤消息
不過,爲了遵循「每一個 throw 必須對應一個 catch」的原則,能夠設置一個頂層的異常處理器來處理漏掉的錯誤。
set_exception_handler()函數可設置處理全部未捕獲異常的用戶定義函數
//設置一個頂級異常處理器
function myexception($e){
echo 'this is top exception';
} //修改默認的異常處理器
set_exception_handler("myexception");
try{
$i=5;
if($i<10){
throw new exception('$i must greater than 10');
}
}catch(Exception $e){
//處理異常
echo $e->getMessage().'<br/>';
//不處理異常,繼續拋出
throw new exception('errorinfo'); //也能夠用throw $e 保留原錯誤信息;
}
建立一個自定義的異常類
class customException extends Exception{
public function errorMessage(){
//error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg;
}
}
//使用
try{
throw new customException('error message');
}catch(customException $e){
echo $e->errorMsg();
}
可使用多個catch來返回不一樣狀況下的錯誤信息
try{
$i=5;
if($i>0){
throw new customException('error message');//使用自定義異常類處理
} if($i<-10){
throw new exception('error2');//使用系統默認異常處理
}
}catch(customException $e){
echo $e->getMessage();
}catch(Exception $e1){
echo $e1->getMessage();
}
須要進行異常處理的代碼應該放入 try 代碼塊內,以便捕獲潛在的異常。
每一個try或throw代碼塊必須至少擁有一個對應的 catch 代碼塊。
使用多個 catch 代碼塊能夠捕獲不一樣種類的異常。
能夠在try代碼內的catch 代碼塊中再次拋出(re-thrown)異常。