

异常处理归类于错误处理,PHP从5.1.0开始增加了Exception异常处理类。
一、异常处理
PHP异常处理与Java相似,都使用try、throw、catch语句,发生异常时代码。如果异常没有被捕获,而且又使用set_exception_handler()函数作相应的处理的话,那么将发生一个严重的错误(致命错误),并且输出 "Uncaught Exception" (未捕获异常)的错误消息。
1、try:
用于可能发生异常的代码块。
2、throw:
规定如何触发(trigger)异常,用于抛出异常。每一个throw必须对应至少一个catch。
3、catch:
捕获异常,并创建包含异常信息的对象。
说明:姑且认为php的异常必须throw才能捕获到。
基本结构:
try{
#some codes
throw new Exception("message"[,code[,...]]);
}
catch(Exception $ex){
#some codes
}二、PHP 异常基类Exception
类摘要:
Exception {
/* 属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $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 )
}示例:
<?php
try {
throw new Exception("Some error message", 30);//抛出异常,设置异常代号为30
} catch(Exception $e) {
echo "Exception:file:".$e->getFile().",message:" . $e->getMessage().",code:".$e->getCode()."line:".$e->getLine();
}
?>三、自定义异常类
实例:
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("这是自定义异常。");
}
catch(customException $ex){
#some codes
}四、多catch捕获异常
当一个try语句中可能抛出不同的异常时,对应的可有多个catch块捕获不同类型异常。同java中的一些注意点:
1、大异常catch放后面。因为抛出异常时按顺序判断先满足哪个catch,一次仅执行一个catch。
2、执行一次try,最多执行一个catch(发生异常时),即若前面某个catch满足执行,则后面的catch不再考虑。
推荐教程:PHP视频教程
