【问题标题】:Discriminating between different PHP exceptions区分不同的 PHP 异常
【发布时间】: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 CommonInputExceptionsUserInputTooLong等也一样;然后只是赶上Common..Exc
  • “所有预期的异常几乎都以相同的方式处理”与“我如何根据异常执行不同的操作”。选择一个。
  • @mario 啊,也许吧。我从来没有这样做过,但会阅读手册。谢谢

标签: php exception exception-handling try-catch


【解决方案1】:

通过使用不同的异常。即

class ExceptionOne extends Exception {}
class ExceptionTwo extends Exception {}

try {
    $user_input=$_POST['user_input'];
    // rest of code here...
    if (test1($user_input)) {
        throw new ExceptionOne("Anticipated exception 1."); 
    }
    // rest of code here...
    //Some PDO which might generate a non-anticipated exception  
    if (test2($user_input)) {
        throw new ExceptionTwo("Anticipated exception 2."); 
    }
    // rest of code here...
}
catch (ExceptionOne $e) {
    /*...*/
}
catch (ExceptionTwo $e) {
    /*...*/
}

同时检查预定义的例外情况,这可能有助于将您的例外情况分组:http://php.net/manual/en/spl.exceptions.php

【讨论】:

  • 谢谢约翰内斯。 PDO 异常会在哪里捕获?我可以把catch (Exception $e) {throw $e;}放在最后吗?
  • PDO 抛出 PDOException,所以你 catch (PDOException $e) php.net/pdoexception
  • 啊,没关系。没有想。如果发生了 PDO 异常,它不会被捕获,那么为什么要捕获它并再次抛出它。谢谢,明白了!
  • @user1032531 如果你没有在捕获中做任何事情,那么捕获错误只是为了重新抛出它真的没有意义。哈,我看到你在我发表评论前 4 秒就意识到了这一点 :)
  • 捕获来自 PDO 之类的异常并将它们包装在自定义类型中会很好。即catch(PDOExcpetion $e) { throw new MyModuleException("failed to receive data", 0, $e); } 然后即使您替换数据库,其他代码也可以捕获MyModuleException。当这样做时,将原始异常(第三个参数传递给异常的构造函数)传递,以便在调试时找到原点php.net/exception.getprevious
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 2012-02-21
  • 2018-11-11
相关资源
最近更新 更多