限时免费试用:欢迎注册 api.bigmodel.org ,快速体验大模型 API 接入服务。
当前位置:首页 >开发者 >PHP笔记 >PHP高级

OOP面向对象基础-错误处理

分类:PHP高级时间:2018-01-04浏览:3405

try{}catch(){}

try{
        要测试的语句,带有(抛出一个错误对象)throw new Exception('出错啦',100);
  }catch(Exception $a){
        $a->getMessage();
class A
{
    private $age='200';
    public function show ()
    {
        if($this->age > 150 || $this->age < 0 ){
            throw new Exception('年龄错误');
        }
    }
}

try{
    $a = new A;
    $a->show();
}catch(Exception $a){
    echo $a->getMessage();
}

异常信息

class A
{
    private $a=0;
    public function show()
    {
        if($this->a == 0){
            throw new Exception('不能为0',100);//编号
        }
    }
}

try{
    $a = new A;
    $a->show();
}catch(Exception $a){
    echo $a->getMessage();//异常消息
    echo $a->getCode();//异常编号(编号可自定义)
    echo $a->getFile();//异常文件  E:\WWW\lianxi\0104\5.php
    echo $a->getLine();//异常行数
    var_dump($a->getPrevious());//NULL

    var_dump($a->getTrace());//以数组的形式展示具体内容
    //array(1) { [0]=> array(6) { ["file"]=> string(24) "E:\WWW\lianxi\0104\5.php" ["line"]=> int(30) ["function"]=> string(4) "show" ["class"]=> string(1) "A" ["type"]=> string(2) "->" ["args"]=> array(0) { } } }

    var_dump($a->getTraceAsString());
    //string(52) "#0 E:\WWW\lianxi\0104\5.php(30): A->show() #1 {main}"
}

自动接收异常set_exception_handler()

function autoException(Exception $a){
    echo $a->getMessage();
}

set_exception_handler('autoException');//函数名,,,带引号////

function s($a,$b)
{
    if($b == 0){
        throw new Exception('除数不能为0');
    }
    return $a/$b;
}

s(10,0);
本站文章如未注明出处均为原创,转载请注明出处,如有侵权请邮件联系站长。
0/500
Share your thoughts respectfully.