7.1. 异常 ,exception类

未匹配的标注

持之以恒,方得始终!

什么是异常处理?

异常是可扩展,可维护,面向对象的,给处理错误提供了统一的机制。

try {
    // your code
}

把要执行的代码放到 try 中,如果有错误,我们可以抛出异常:

throw new Exception('message', 'code');

throw 接受一个对象数据,然后抛出异常。最简单的就是 new 一个内置的 Exception异常类。

Exception类 的构造函数需要两个参数,一个消息文本(错误消息),一个代码(错误代码号),这两个参数是可选的。我们可以使用之前学习过的反射 Reflection 来看类的内部细节。

抛出异常后,我们还至少得给一个 catch块,来处理发生错误后的处理工作,或者说捕获异常后,我们还得干点什么:

catch (类声明 对象) {

}

一个 try{ } 可以有多个 catch{ }。

整个异常处理机制

  • try 中执行业务代码,有错误,throw 抛出一个异常类的对象。
  • catch 捕获这个对象,然后处理错误情况。

这种异常类,可以是内置的 Exception类,或者是继承它后,我们自己写的子类,或者是专门写的一个异常类。

当有一个异常抛出时,php会查找匹配它的 catch块,如果有多个 catch块,那传给每个 catch块 的对象需要不同。

注意:在一个 catch块中,还可以产生新的异常。

try {
    throw new Exception('a error occurred', 42);
}

catch (Exception $e) {
    echo $e->getCode() . "\n" . $e->getMessage() . "\n" . $e->getFile() . "\n" . $e->getLine();
}

Exception类

  • 构造方法,需要两个可选的参数,error_message , error_code
  • getCode() 返回传给构造方法的代码。
  • getMessage() 返回传给构造方法的消息。
  • getFile() 返回产生异常的代码文件的完整路径。
  • getLine() 返回代码文件中产生异常的代码行号。
  • getTrace() 执行过的函数的回溯数组
  • getTraceAsSting() 数组转为字符串
  • __toString()

Exception类的大概代码示例

class Exception {
    protected $message = "Unknow exception";
    protected $code    = 0;
    protected $file;
    protected $line;

    private $trace;
    private $string;

    function __construct(string $message = null, int $code = 0) {
        if (func_num_args()) {
            $this->message = $message;
        }
        $this->code = $code;
        $this->file = __FILE__;
        $this->line = __LINE__;
        $this->trace = debug_backtrace();
        $this->string = StringFormat($this);
    }

    final function getMessage() {
        return $this->message();
    }

    final function getCode() {
        return $this->code;
    }

    final function getFile() {
        return $this->file;
    }

    final function getTrace() {
        return $this->trace;
    }

    final function getTraceAsString() {
        return self::TraceForamt($this);
    }

    function __toString() {
        return $this->string;
    }

    static private function StringFormat(Exception $exception) {
        // 将类的信息转为字符串形式的信息
    }

    static private function TraceFormat(Exceptipn $exception) {
        // trace转为字符串
    }

}

可以看到,很多方法都被 final 修饰了,也就是不能在子类中重写了,我们可以重写一个 __toString() 方法,或者写新的方法。

自己写一个异常类

我们尝试继承 Exception类,来写一个自己的异常类。

class myException extends Exception {
    function __toString() {
        return "Exception: " . $this->getCode() . $this->getMessage() . " in " . $this->getFile()  . " on line " . $this->getLine();
    }
}

try {
    throw new myException("A new error occurred...", 42);
} catch (myException $m) {
    echo $m;
}

如有任何侵权行为,请通知我删除,谢谢大家!
个人邮箱:865460609@qq.com

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
Junwind
讨论数量: 0
发起讨论 只看当前版本


暂无话题~