我正在使用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 块将被执行,因为 Exception
是 UserException
的父对象,因此任何类型 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.');