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);
}
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;
}
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;
}
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?
Are you asking about what's the different with
$db->connect_error
andtry/catch
?$db->connect_error
mostly for the errors which we already knew (username incorrect, etc.)and
try/catch
is about system level, once an error occur,PHP will search for the nearest try/catch block,
once it catch something, PHP will still continue like nothing happened before,
but if you don't have any
try/catch
block andset_exception_handler()
too,PHP will just stop by the error.
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.
A try catch block essentially works like this
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
See the PHP docs for more information about exceptions http://php.net/manual/en/language.exceptions.php
If you need to catch exceptions on mysqli extension by use try/catch block, try this code (switch on exception mode instead of classic error reporting):
mysqli_sql_exception mysqli_driver