欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php的错误和异常处理

程序员文章站 2024-01-24 16:45:10
...
与java不同,在php中,异常必须手动抛出.

抛出并捕获一个异常,示例:

Exception("A terrible error has occurred",42);
}catch (Exception $e){
    echo "Exception ".$e->getCode().":".$e->getMessage()."
"."in".$e->getFile()." on line".$e->getLine()."
"; }
显示结果:

php的错误和异常处理
Exception类的内置方法:

getCode()——返回传递给构造函数的代码;

getMessage()——返回传递给狗仔函数的消息;

getFile()——返回产生异常的代码文件的完整路径;

getLine()——返回代码文件中产生异常的代码行号

getTrance——返回一个包含了产生异常的代码回退路径的数组;

getTranceAsString——返回与getTrance()方向相同的消息,该消息将被格式化一个字符串;

__toString()——允许简单地显示一个Exception对象,并且给出以上所有方法可以提供的信息。

用户自定义异常示例:

Exception extends Exception{
    function __toString(){
        return "Exception ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
"; } } try{ throw new myException("A terrible error has occurred",42); }catch (myException $m){ echo $m; }

一个应用异常处理的示例:文件I/O处理

首先需要创建一个异常类的文件:file_Exception.php

Exception extends Exception{
    function __toString(){
        return "fileOpenException ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
"; } } //自定义无法写入异常 class fileWriteException extends Exception{ function __toString(){ return "fileWriteException ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
"; } } //自定义无法获得写锁异常 class fileLockException extends Exception{ function __toString(){ return "fileLockException ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
"; } }
再在主文件processorder.php文件中引入file.Exception.php文件

require_once ("file_Exception.php");
异常处理关键代码:

 //设置文件输出内容和格式
    $out_put_string=$date."\t".$cloths."件男装\t".$shoes."双鞋子\t".$glasses."副眼镜\t\总价:¥".$total_amount." 收货地址:\t".$address."\n";

    //异常处理
    try{
        //打开文件,(追加模式+二进制模式)
        if(!($fp=@fopen("$DOCUMENT_ROOT/L02/files/orders.txt",'ab')))
            throw new fileOpenException();
        //写操作锁定
        if(!flock($fp,LOCK_EX))
            throw new fileLockException();
        //将数据写入到文件
        if(!fwrite($fp,$out_put_string,strlen($out_put_string)))
            throw new fileWriteException();
        //释放已有的锁定
        flock($fp,LOCK_UN);
        //关闭文件流
        fclose($fp);
        echo "

数据保存完成

"; }catch (fileOpenException $foe){ echo "

文件打开失败,请查看服务器是否异常!

"; exit; }catch(Exception $e){ echo "

您的订单没有提交完成,请再试一次。

"; exit; }

以上就介绍了php的错误和异常处理,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。