
PHP异常类及异常处理操作
异常处理归类于错误处理,php从5.1.0开始增加了exception异常处理类。
一、异常处理
PHP异常处理与Java相似,都使用try、throw、catch语句,发生异常时代码。如果异常没有被捕获,而且又使用set_exception_handler()函数作相应的处理的话,那么将发生一个严重的错误(致命错误),并且输出 "Uncaught Exception" (未捕获异常)的错误消息。
1、try:
用于可能发生异常的代码块。
立即学习“PHP免费学习笔记(深入)”;
2、throw:
规定如何触发(trigger)异常,用于抛出异常。每一个throw必须对应至少一个catch。
3、catch:
捕获异常,并创建包含异常信息的对象。
说明:姑且认为php的异常必须throw才能捕获到。
基本结构:
try{
#some codes
throw new Exception("message"[,code[,...]]);
}
catch(Exception $ex){
#some codes
}二、PHP 异常基类Exception
该软件是以php+MySQL进行开发的金融企业类网站源码,运行网站提示填写mysql数据库信息,网站将自行安装。后台地址:http://您的网址/admin/ 默认用户名和密码admin成都艾威尔网络科技有限公司(IVEARS)成立于2012年,主要致力于网站建设,网页设计,网站制作开发及网络营销领域。 服务项目包含了网页设计、网站程序开发、域名注册、国内外空间申请、CMS系统开发、微网站制
类摘要:
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异常对象主要包含异常的文本信息(message)、异常代码/代号(code,应该是用于开发人员标识)、异常发生的文件(file,即发生异常的php文件)、异常发生的具体位置(line,抛出异常的行号)。
示例:
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()
.': '.$this->getMessage().' 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视频教程










