[英]How do I raise PDOException?
This code works fine, but I'll want to handle exception
if any thing goes wrong, so I deliberately made a syntax error in the query
but nothing happens. 这段代码工作正常,但如果出现任何问题,我会想要处理
exception
,所以我故意在query
出现语法错误,但没有任何反应。 Below is the code 下面是代码
try {
$sql = "INSERT INTO journals (topic, author, ) VALUES ('$topic', '$authors', ')";
echo "1st";
$lecturers_db->query($sql);
echo "second";
} catch(PDOException $e) {
echo $e->getMessage();
echo $msg = "Error!";
}
Without the obvious syntax error, the code works fine but with the syntax error, nothing happens, all the code in the try block
executes and the code in the catch block
never executes. 没有明显的语法错误,代码工作正常,但是语法错误,没有任何反应,
try block
中的所有代码都执行, catch block
的代码永远不会执行。
I want to raise an exception
, please how do I do it here, thanks for any help. 我想提出一个
exception
,请在这里怎么做,谢谢你的帮助。
Be sure to set the attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION , as soon as you init your pdo object: 请务必将属性PDO :: ATTR_ERRMODE只要你初始化你的PDO对象设置为PDO :: ERRMODE_EXCEPTION,:
$lecturers_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
After that, any failed queries will raise an exception 之后,任何失败的查询都会引发异常
Exceptions are thrown. 抛出异常。 Syntax errors in code != Exceptions.
代码中的语法错误!=异常。
<?php
try {
$code = 12;
throw new PDOException('Message', $code );
} catch (PDOException $e) {
}
?>
However, from the maual : 但是,来自maual :
You should not throw a PDOException from your own code.
您不应该从自己的代码中抛出PDOException。 See Exceptions for more information about Exceptions in PHP.
有关PHP中的异常的更多信息,请参阅异常。
My advice is to throw either a general exception, or to write your own custom exception to handle your error. 我的建议是抛出一般异常,或编写自己的自定义异常来处理错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.