用于要求调用方法的内置异常



假设你想要求在调用另一个方法之前先调用某个方法。是否有适当的内置例外?例如,

class Foo
{
    private $bar;
    public function getBar()
    {
       if (!$this->bar)
          throw new Exception('must call setBar() first');
        return $this->bar;
    }
    public function setBar($bar)
    {
        $this->bar = $bar;    
    }
}

在此示例中,哪个内置异常是泛型Exception的适当替代?

这是 php7 的官方异常层次结构

http://php.net/manual/en/spl.exceptions.php


引起我注意的例外情况是

LogicException

  • 表示程序逻辑中的错误的异常。这种异常应直接导致代码中的修复。

BadMethodCallException

  • 如果回调引用未定义的方法或缺少一些参数。

BadMethodCallException似乎不太合适,而LogicException听起来像是所有内置例外中最好的。

最新更新