[英]Exception is not thrown in php pdo
I am trying to throw an exception in PHP but it does not throw. 我正在尝试在PHP中引发异常,但不会引发异常。 When I deliberately give password string (although I am not having a password on my
localhost
) it gives this error: 当我故意提供密码字符串(尽管我在
localhost
上没有密码)时,出现以下错误:
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES).
SQLSTATE [HY000] [1045]用户'root'@'localhost'的访问被拒绝(使用密码:是)。
While it should be throwing my custom error message. 虽然应该抛出我的自定义错误消息。 Again if I deliberately write
localhost
as focalhost
or change username from root
to hoot
, it does not throw my custom exception message. 再次,如果我故意写
localhost
作为focalhost
或更改用户名root
来hoot
,不投我的自定义异常消息。
<?php
try{
$con = new PDO("mysql:host = localhost; dbname = chatdump", "root","");
if(!$con){
throw new Exception("There was some error connecting to database");
}
}
catch(Exception $e){
echo $e->getMessage();
}
?>
An exception stops the further execution, and therefore your condition is never executed. 异常会停止进一步执行,因此永远不会执行您的条件。
But what is more important, your idea on throwing such a custom but useless error message is wrong. 但是更重要的是,您关于引发此类自定义但无用的错误消息的想法是错误的。 You should never rewrite a useful precise error message to just a vague notice.
您永远不要将有用的精确错误消息重写为模糊的通知。
What you should be doing is leaving your PDOException alone, and then catch it somewhere, and then handle it. 您应该做的就是让您的PDOException独处,然后将其捕获到某个地方,然后对其进行处理。 It could be either a global try-catch for the whole code, or a dedicated error handler.
它可以是整个代码的全局try-catch,也可以是专用的错误处理程序。
You should understand that there are two distinct kinds of people who needs to be informed of the error: the staff in charge of the site and site visitors. 您应该了解,需要将错误告知两种不同的人:负责站点的人员和访问者。 And both require completely different error messages.
两者都要求完全不同的错误消息。 But you are depriving the former from the error message they need to resolve a problem with the site.
但是您使前者摆脱了他们需要解决该网站问题的错误消息。
So what you should be doing 所以你应该做什么
Recently I wrote an article on PHP error reporting which you may find interesting to read. 最近,我写了一篇有关PHP错误报告的文章,您可能会觉得有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.