PHP尝试/捕获和致命错误 [英] PHP try/catch and fatal error
问题描述
我正在使用以下脚本通过PHP使用数据库:
I'm using the following script to use a database using PHP:
try{
$db = new PDO('mysql:host='.$host.';port='.$port.';dbname='.$db, $user, $pass, $options);
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
现在,我想使用此数据库句柄使用以下代码进行请求:
Now, I want to use this database handle to do a request using this code:
try{
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(array(
'...' => $...,
'...' => $...
));
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
问题出在这里
- 与数据库的连接正常后,一切正常,
- 当连接失败但我不使用数据库时,我拥有
$GLOBALS['errors'][]
数组,此后脚本仍在运行, - 与数据库的连接失败时,出现以下致命错误:
- When the connection to the DB is OK, everything works,
- When the connection fails but I don't use the DB, I have the
$GLOBALS['errors'][]
array and the script is still running afterwards, - When the connection to the DB has failed, I get the following fatal error:
注意:未定义的变量:第32行的C:\ xampp \ htdocs [...] \ test.php中的数据库
Notice: Undefined variable: db in C:\xampp\htdocs[...]\test.php on line 32
致命错误:在第32行的C:\ xampp \ htdocs [...] \ test.php中的非对象上调用成员函数prepare()
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs[...]\test.php on line 32
注意:第32行是$query = $db->prepare(...)
指令.
也就是说,脚本崩溃了,并且try/catch似乎没有用.您知道为什么第二次尝试/捕获不起作用以及如何解决吗?
That is to say, the script crashes, and the try/catch seems to be useless. Do you know why this second try/catch don't works and how to solve it?
感谢您的帮助!
编辑:有一些非常好的答复.我已经验证了一种不完全是我想要做的方法,但这可能是最好的方法.
There are some really good replies. I've validated one which is not exactly what I wanted to do, but which is probably the best approach.
推荐答案
try
/catch
块仅适用于抛出的异常(必须调用throw Exception
或Exception
的子类).您无法使用try
/catch
捕获致命错误.
try
/catch
blocks only work for thrown exceptions (throw Exception
or a subclass of Exception
must be called). You cannot catch fatal errors using try
/catch
.
如果无法建立数据库连接,我认为这是致命的,因为您可能需要数据库来执行页面上有意义的任何事情.
If your DB connection cannot be established, I would consider it fatal since you probably need your DB to do anything meaningful on the page.
PDO
将引发异常.您的特定问题是,当尝试使用$db
调用方法时未定义它,因此您会得到致命的空指针(某种).而不是像其他人所建议的那样跳过if ($db == null)
箍,您应该修复代码以确保在需要时始终定义$db
,或者采用不太脆弱的方式来确保数据库连接可用.使用它的代码.
PDO
will throw an exception if the connection cannot be established. Your specific problem is that $db
is not defined when you try to call a method with it so you get a null pointer (sort of) which is fatal. Rather than jump through if ($db == null)
hoops as others are suggesting, you should just fix your code to make sure that $db
is either always defined when you need it or have a less fragile way of making sure a DB connection is available in the code that uses it.
如果您真的想捕获"致命错误,请使用set_error_handler
,但这仍然会在发生致命错误时停止脚本执行.
If you really want to "catch" fatal errors, use set_error_handler
, but this still stops script execution on fatal errors.
这篇关于PHP尝试/捕获和致命错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!