尝试/捕获mysqli [英] Try / catch in mysqli

查看:51
本文介绍了尝试/捕获mysqli的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习OOP mysqli课程.连接到数据库时,他们使用以下脚本:

I'm following an OOP mysqli course. When connecting to the database, they use the following script:

$db = new mysqli("host", "user", "password", "database");
if ($db->connect_error){
    $error = $db->connect_error;
    echo("Not connected: " . $error);
}

不过,他们后来使用try/catch块调用数据库连接文件:

Later though, they call the database connection file with a try / catch block:

try {
    require_once "connection.php";
}catch (Exception $e){
    $error = $e->getMessage();
    echo $error;
}

尝试连接后,连接文件是否立即处理了可能的连接错误? try/catch块基本上在做同样的事情吗?还是try/catch块正在寻找其他类型的错误?

Isn't a possible connection error being handled by the connection file immediately after trying to connect? Is the try / catch block basically doing the same thing? Or is the try / catch block looking for a different type of error?

更新:在阅读了一些答案之后,请澄清一下.当我这样做时:

UPDATE: Just to clarify, after reading some of the answers. When I just do this:

try {
    $db = new mysqli("host", "user", "password", "database");
}catch (Exception $e){
    $error = $e->getMessage();
    echo $error;
}

假设数据库访问数据是错误的(例如错误的主机),我会收到PHP警告,但在catch块中不会收到错误输出.捕获是否不应该检测到此错误?

assuming that the database access data is wrong (for example a wrong host), I get a PHP warning but not the error output in the catch block. Shouldn't the catch detect this error?

推荐答案

在代码的第一部分中,如果使用if语句,您将检查该条件是否为真,然后输出消息.

In the first section of code when you use the if statement, you are checking to see if that one condition is true and then outputting your message.

try catch块本质上是这样的

A try catch block essentially works like this

try{
   //place code here that could potentially throw an exception
}
catch(Exception $e)
{
  //We will catch ANY exception that the try block will throw

}

因此,您会看到,当if语句检查预期的条件时,try catch块将检测出任何出错的内容,甚至是您没有预料到的内容. 因此,在调试时,您可以更改catch块中的代码以处理您认为合适的异常

So you see that while your if statement is checking for a condition that you are anticipating, the try catch block will detect anything that goes wrong, even those things that you don't anticipate. Therefore, when debugging you can alter the code in the catch block to deal with exceptions as you see fit

有关异常的更多信息,请参见PHP文档. http://php.net/manual/zh/language.exceptions.php

See the PHP docs for more information about exceptions http://php.net/manual/en/language.exceptions.php

这篇关于尝试/捕获mysqli的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆