
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
类摘要:
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();
}
?>三、自定义异常类
实例:
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视频教程
以上就是PHP项目异常类该如何设计的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号