小叮当的肚兜 2019-01-24 16:52:04 3285次浏览 1条评论 1 1 0

PHP 的异常类继承自 Throwable 接口类,2个经常使用的类:
ErrorException
看下Throwable代码:

interface Throwable
{
    /**
     * 获取异常信息
     */
    public function getMessage();

    /**
     * 获取异常码
     */
    public function getCode();

    /**
     * 获取抛出异常的文件
     */
    public function getFile();

    /**
     * 获取抛出异常的代码行号
     */
    public function getLine();

    /**
     * 获取异常堆栈跟踪 返回数组
     */
    public function getTrace();

    /**
     * 获取异常堆栈跟踪 返回字符串
     */
    public function getTraceAsString();

    /**
     * 继承 Throwable接口的异常类 实例化传入的第三个参数
     */
    public function getPrevious();

    /**
     * 魔术方法
     */
    public function __toString();
}

举例说明 Exception

class Exception implements Throwable {
    protected $message;
    protected $code;
    protected $file;
    protected $line;
    
    /**
     * 不允许克隆 会抛异常
     */
    final private function __clone() { }

    /**
     * 实例化.
     */
    public function __construct($message = "", $code = 0, Throwable $previous = null) { }

    /**
     * 魔术方法
     */
    public function __wakeup() { }
}

关于 $previousstackoverflow 中 找到解释,

try {
    throw new FooException('Foo exception');
} catch (FooException $e) {
    $code = 1;
    throw new BarException('Bar exception', $code, $e);
}

yii2 的异常类 就是子类继承父类形成一个树,这样划分的好处很多。方便查找错误,一目了然。
看下分布图:
image

异常处理 就是使用 try catch finally,finally 我是用的少。意思就是最后总会执行(除非没有抓到异常错误)。不过有点要注意
抛出的 Error 异常,通过 catch Exception 是抓不到的。

try{
    throw new \Error('Error');
}catch (\Exception $e){
    echo 'Exception <br>';
}finally{
    echo 'finally <br>';
}

通常抛出Error类错误就是代码有问题了。但是若果想抓到可以这样写:

try{
    throw new \Error('Error');
}catch (\Throwable $e){
    echo 'Throwable <br>';
}catch (\Exception $e){
    echo 'Exception <br>';
}finally{
    echo 'finally <br>';
}
觉得很赞
您需要登录后才可以评论。登录 | 立即注册