PDO fetch() 是否会在失败时抛出异常?

2022-01-20 00:00:00 exception-handling fetch php mysql pdo

方法 PDOStatement::fetch() 是否会抛出异常失败,如果PDO错误报告系统设置为抛出异常?例如.如果我设置:

Does the method PDOStatement::fetch() throw an exception on failure, if the PDO error reporting system is set to throw exceptions? E.g. if I set:

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION

你知道这样的案例吗?

非常感谢.

PdoStatement::fetch 方法确实会在失败时抛出异常,而不是 FALSE.我的回答中证明了这种情况:

The method PdoStatement::fetch throws indeed exceptions on failure, instead of FALSE. Such a case is demonstrated in my answer:

  • 模拟 PDO 获取失败情况

总结:

  • PDOStatement::fetch 如果没有找到记录,则返回 FALSE.
  • PDOStatement::fetch 失败时抛出异常.
  • PDOStatement::fetch returns FALSE if no records are found.
  • PDOStatement::fetch throws exceptions on failure.

推荐答案

用户 here 声称 fetch() 引发了异常.我会非常小心地假设它不会或不会抛出异常,因为它们通常在您准备或绑定时抛出.这是将调用放在 try 块中的一个很好的理由.所以要回答这个问题,在极不可能发生的失败事件中,是的 fetch() 应该抛出一个异常,在这种情况下它确实发生了.现在看看是否还有其他情况会很有趣.

The user here claims that fetch() threw an exception. I'd be very careful in assuming that it doesn't or won't throw an exception just because they are typically thrown when you prepare or bind. This is a very good reason to put the call inside a try block. So to answer the question, in the highly unlikely event of failure, yes fetch() should throw an exception and in that one case it did. Now it will be interesting to see if there are other cases as well.

相关文章