在使用 Yii 2 时遇到扩展异常的问题


Having issue with extended exceptions using Yii 2

我正在使用Yii 2框架,它使用了许多扩展异常,我遇到了问题,我扔了一个UserException,但它最终被基本Exception捕获,但我不确定为什么!?

代码:

try {
    //........
    if ($reader->count() > 0) {     
        if (!$already_active) {         
            //.....
        } else {
            throw new UserException('You have already activated your account; you may continue to login.');             
        }
    }
} catch ('Exception $e) {
    // User exception above is caught in here?
} catch (UserException $e) {
    // Rethrow the exception
    throw $e;
}

难道不应该把User Exception传给第二个catch并抓住吗?

来自 http://php.net/manual/en/language.exceptions.php

当抛出异常时,语句后面的代码将不会执行,PHP 将尝试查找第一个匹配的 catch 块。

Exception的 catch 块将被执行,因为 ExceptionUserException 的父对象,因此任何类型 UserException 的对象也是 Exception 类型。

因此,您应该重构代码以首先为子类提供 catch 块。在您的情况下,UserException应该是第一位的。

如果你

看一下UserException类,你可以看到:

class UserException extends Exception

因此,Exception具有更高的优先级。

但是,您可以只做:

//if something's wrong
throw new 'yii'base'UserException('You have already activated your account; you may continue to login.');