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

Bre*_*ett 1 php exception-handling try-catch yii yii2

我正在使用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;

}
Run Code Online (Sandbox Code Playgroud)

不应该User Exception被传递到第二个并被第二个捕获catch

top*_*her 5

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

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

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

因此,您应该重构代码以首先获得子类的catch块.在你的情况下UserException应该是第一个.