我想捕获自定义异常,对其进行一些逻辑处理,如果失败,则将其扔到更通用的 catch block 中。像这样:
class My_Exception extends Exception {
protected $_nonFatal = false;
public function __construct($value, $nonFatal = false) {
$this->_nonFatal = (bool)$nonFatal;
return parent::__construct($value);
}
public function isNonFatal() {
return (bool)$this->_nonFatal;
}
}
try {
} catch (My_Exception $e) {
if ($e->isNonFatal) {
// #1
// Err gently
}
// #2
// The error was fatal, so keep throwing it
throw new Exception($e->getMessage());
} catch (Exception $e) {
// #3
echo 'An exception was caught with the message '.$e->getMessage();
}
所以我捕获了 My_Exception
,检查它是否是非 fatal error 。如果是这样,请轻轻地犯错(第 1 节)。如果不是(第 #2 节),我希望触发第二个捕获(第 #3 节)。相反,第 #2 节中的 throw new Exception
离开 try/catch/catch
一起。
我可以在 $e
的类上使用 switch 语句,但我认为那样比较麻烦。是否有我缺少的标准方法来执行此操作?
最佳答案
If not (section #2), I want the second catch to be triggered
try/catch block 不是这样工作的——catch block 总是会跳出 try/catch block ;它不会像 switch 语句那样“落空”。
您需要用另一个 try/catch block 包装您的代码。
try {
try {
// ...
} catch (My_Exception $e) {
if ($e->isNonFatal) {
// #1
// Err gently
}
// #2
// The error was fatal, so keep throwing it
throw new Exception($e->getMessage());
}
} catch (Exception $e) {
// #3
echo 'An exception was caught with the message '.$e->getMessage();
}
Is there a standard way to do this that I'm missing?
也没有真正的“标准”方法来做到这一点;通常您不会用另一个异常来概括一个异常,但如果应用程序是正确的,那么这就是您想要的方式。
管理异常链的更好方法是 pass your custom exception a the previous exception在构造函数中。那样的话,无论什么选择异常,都有可能使用 Exception.getPrevious()
,并将您的异常与更通用的异常一起显示。
关于php - 将异常抛出到下一个 Catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348242/