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)异常。