In the distribution code of pset7, there is a file functions.php
containing the function query()
.
In this function there is a try
block followed by a catch
block; what purpose do they serve?
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.
Sign up to join this communityAn exception is sort of a tolerable error. When you write some code that might throw an exception, you better enclose it with a try block. If an exception occurred, you may catch it with a catch block.
Basically, catch blocks contain code (usually to display an error message) to be interpreted when the specified exception is caught (aka exception handling).
The try/catch block in query()
try
{
// connect to database
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
// ensure that PDO::prepare returns false when passed invalid SQL
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
// trigger (big, orange) error
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
basically tries to connect to a database using the given information (e.g., the name of the database, the username, etc). If the connection to the database was failed, this code throws an exception.
Now, how do I know that? Well, looking at the manual of PDO
, under the Errors/Exceptions section
PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.
PDOException
is an indirect subclass of Exception
which is caught by the catch block. If this exception was caught, the code within the catch block is interpreted. If, however, no exceptions were caught, the catch block is ignored and the first statement immediately after it is interpreted.
As for your question
Can't we use simple if-else statements rather than try-catch thing? If not, why?
Well, the try/catch block was made specifically to serve that purpose -- catch and handle exceptions. I'm not sure whether you can handle exceptions using if/else statements, but I'm sure that it's a best practice to handle it using try/catch blocks.
if-else
statements rather thantry-catch
thing? If not, why? Thank you @sinister