php – Exception,InvalidArgumentException或UnexpectedValueException之间有什么区别?

我什么时候应该使用Exception,invalidargumentexception或UnexpectedValueException?

我不知道它们之间真正的不同,因为我总是使用Exception.

不同的异常只会为您提供更多的粒度并控制您捕获和处理异常的方式.

考虑一个你正在做很多事情的课 – 例如获取输入数据,验证输入数据,然后将其保存在某处.您可能会认为如果将错误或空参数传递给get()方法,则可能会抛出invalidargumentexception.验证时,如果某些内容不正常或不匹配,则可能抛出UnexpectedValueException.如果发生完全意外的事情,您可以抛出标准异常.

当你捕捉时,这变得很有用,因为你可以用不同的方式处理不同类型的异常.例如:

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');
    }
}

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

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)“您传递的值与架构不匹配…例外:Var应该是12个字符长.”.

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...