【发布时间】:2016-05-31 14:45:44
【问题描述】:
我有一些难以阅读的 IF/THEN 逻辑,我正在考虑改用异常。
代码将测试用户输入,并在适当的时候抛出异常。我的 catch 语句将处理预期的异常,但如果不是预期的异常(就像我搞砸了 PDO 语句),我希望抛出异常并让 PHP 的错误系统处理它。所有预期的异常几乎都以相同的方式处理,我不希望在每个测试周围使用多个 try/catch。
在 catch 语句中,如何根据异常执行不同的操作?
try {
$user_input=$_POST['user_input'];
// rest of code here...
if (test1($user_input)) {
throw new Exception("Anticipated exception 1.");
}
// rest of code here...
//Some PDO which might generate a non-anticipated exception
if (test2($user_input)) {
throw new Exception("Anticipated exception 2.");
}
// rest of code here...
}
catch (Exception $e) {
if(anticipatedException($e)) {
//Deal with it
}
else {
throw $e;
}
}
【问题讨论】:
-
您不能将您的特定例外归为一个共同的祖先吗?
-
@mario 我不明白。请详细说明。
-
如
UserInputTooShortExc extends CommonInputExceptions和UserInputTooLong等也一样;然后只是赶上Common..Exc。 -
“所有预期的异常几乎都以相同的方式处理”与“我如何根据异常执行不同的操作”。选择一个。
-
@mario 啊,也许吧。我从来没有这样做过,但会阅读手册。谢谢
标签: php exception exception-handling try-catch