【问题标题】:What is the difference between Exception, InvalidArgumentException or UnexpectedValueException?Exception、InvalidArgumentException 或 UnexpectedValueException 之间有什么区别?
【发布时间】:2015-09-24 04:01:35
【问题描述】:

什么时候应该使用 Exception、InvalidArgumentException 或 UnexpectedValueException?

我不知道它们之间的真正区别,因为我总是使用异常。

【问题讨论】:

标签: php exception error-handling throw


【解决方案1】:

不同的异常只会让您更细致地控制如何捕获和处理异常。

考虑一个你正在做很多事情的课程 - 例如。获取输入数据,验证输入数据,然后将其保存在某处。您可能会决定,如果将错误或空参数传递给get() 方法,您可能会抛出InvalidArgumentException。验证时,如果有异常或不匹配,您可以抛出UnexpectedValueException。如果发生完全出乎意料的事情,你可以抛出一个标准的Exception

这在您捕获时非常有用,因为您可以以不同的方式处理不同类型的异常。例如:

class Example
{
    public function get($requiredVar = '')
    {
        if (empty($requiredVar)) {
            throw new InvalidArgumentException('Required var is empty.');
        }
        $this->validate($requiredVar);
        return $this->process($requiredVar);
    }

    public function validate($var = '')
    {
        if (strlen($var) !== 12) {
            throw new UnexpectedValueException('Var should be 12 characters long.');
        }
        return true;
    }

    public function process($var)
    {
        // ... do something. Assuming it fails, an Exception is thrown
        throw new Exception('Something unexpected happened');
    }
}

在上面的示例类中,当调用它时,您可以catch 多种类型的异常,如下所示:

try {
    $example = new Example;
    $example->get('hello world');
} catch (InvalidArgumentException $e) {
    var_dump('You forgot to pass a parameter! Exception: ' . $e->getMessage());
} catch (UnexpectedValueException $e) {
    var_dump('The value you passed didn\'t match the schema... Exception: ' . $e->getMessage());
} catch (Exception $e) {
    var_dump('Something went wrong... Message: ' . $e->getMessage());
}

在这种情况下,您会得到一个 UnexpectedValueException,如下所示:string(92) "The value you passed didn't match the schema... Exception: Var should be 12 characters long."

还应该注意these exception classes all end up extending from Exception 无论如何,所以如果你没有为InvalidArgumentException 或其他人定义特殊的处理程序,那么它们无论如何都会被Exception 捕获器捕获。那么真的,为什么不使用它们呢?

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 1970-01-01
    • 2017-09-22
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    相关资源
    最近更新 更多