PHP|异常的使用,异常子类化的最佳实践

构造异常的子类。

class XmlException extends Exception{    private $error;    function __construct(LibXmlError $error) {        $shortfile = basename($error->file);        $msg = "[{$shortfile}, line {$error->line}, col {$error->column} {$error->message}]";        $this->error = $error;        parent::__construct(%msg, $error->code);    }    function getLibXmlError() {        return $this->error    }}class FileException extends Exception{}class ConfException extends Exception{}

代码的逻辑功能部分

// Conf Classfunction __construct($file) {    $this->file = $file;    if (!file_exists($file)) {        throw new FileException();    }    $this->xml = simplexml_load_file($file, null, LIBXML_NOERROR);    if (!is_object($this->xml)) {        throw new XmlException();    }    print gettype($this->xml);    $matches = $this->xml->xpath("/conf");    if (!count($matches)) {        throw new ConfException();    }}function write() {    if (!is_writeable($this->file)) {        throw new FileException("");    }    file_put_contents($this->file, $this->xml->asXML());}

如何使用异常的子类?

class Runner {    static function init() {        try {        } catch (FileException $e) {            // 文件权限或文件不存在        } catch (XmlException $e) {            // XML文件损坏        } catch (ConfException $e) {            // 错误的XML文件格式        } catch (Exception $e) {            // 后备捕捉器,正常情况下不应该被调用。        }    }}

这样,可以在细化的catch子句中,针对不同的错误使用不同的恢复或失败机制。可以决定停止执行程序、记录错误、并继续执行程序,或显式地再次抛出错误。

try {    // ...} catch (FileException $e) {    throw $e;}

参考

  1. 深入PHP,面向对象、模式与实践

关键字:php, 异常, exception


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部