PHP异常类及异常处理操作实例详解 |
|
本文标签:PHP,异常类,异常处理 本文实例讲述了PHP异常类及异常处理操作 。分享给大家供大家参考,具体如下: 异常处理归类于错误处理,PHP从5.1.0开始增加了Exception异常处理类 。 一、异常处理 PHP 异常处理与Java相似,都使用try、throw、catch语句,发生异常时代码 。如果异常没有被捕获,而且又没用使用 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异常对象主要包含异常的文本信息(message)、异常代码/代号(code,应该是用于开发人员标识)、异常发生的文件(file,即发生异常的php文件)、异常发生的具体位置(line,抛出异常的行号) 。 示例:
<?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();
}
?>
浏览器打印结果:
关于php中类与对象的基础(如方法调用),具体看类与对象小节 。 三、自定义异常类 示例:
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不再考虑 。(常见考题) 五、嵌套抛出异常 结构示例:
try{
try{
throw new Exception("第一个异常");
}
catch(Exception $e1){
#相关处理
throw new Exception("处理后抛出异常");//再次抛出异常
}
}
catch(Exception $e2){
#相关处理
}
六、设置顶层异常处理器
示例:
<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>
结果:
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP错误与异常处理方法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》 希望本文所述对大家PHP程序设计有所帮助 。 您可能感兴趣的文章:
|