【发布时间】:2016-03-07 01:42:20
【问题描述】:
我之前在 SO 上看到过这个问题,但似乎没有一个答案是完整的。所以请...
我有使用 PDO 和 PDOStatement 的代码。它最初是为无例外地工作而编写的,我正在将其转换为可以使用。
我的简单问题是:
- 有没有必要继续检查函数的返回值是否为FALSE(当这意味着“失败”),或者我可以简单地执行该方法并假设各种失败都会触发例外?我在一个答案中看到了一个示例,建议有人同时使用 try-catch 和测试 FALSE 的返回值 - 这实际上是必要的,这会产生一些非常丑陋的代码。
- 是否有正确的列表列出哪些方法可以抛出异常,哪些永远不能抛出异常?我看到答案说“如果您发现我们没有记录我们抛出的异常,请提出错误”,但这并不完全有帮助。我已经看到“手册页说明何时可以引发异常”的声明,但是 PDO::query 和 PDOStatement::execute 页面没有提及异常 - 这肯定不可能是真的......可以吗?本质上,我想知道是否准备、绑定 [事物]、获取 [全部]、执行以及其他一些可能或永远不会扔东西。
我不觉得我在问地球,如果需要我可以查看代码,但是关于这方面的手动文档肯定应该是坚如磐石的。
[编辑以添加示例]
我现在发现自己有这样的代码块——我想通过删除返回值的测试来简化它,但我无法说服自己它是正确的。其他块使用execute()等。
try {
/* I do not know whether beginTransaction throws an exception when it would otherwise return FALSE.
* If it does then checking the return value is spurious, and the code cam be simplified.
*/
if (FALSE == $customerDb->beginTransaction()) {
Log::add("Database begin transaction failed.",
Log::ERROR);
throw new Exception("Failed to begin a transaction.");
}
} catch (PDOException $e) {
/* The documentation does not mention the possibility of
* beginTransaction() throwing any exception,
* even when we have configured all the other functions to do so.
*/
Log::add("Database begin transaction threw an exception: " . $e->getMessage(),
Log::ERROR);
throw new Exception("Begin transaction threw an exception.");
}
【问题讨论】:
标签: php postgresql exception pdo