Try and Catch (…me if you can)

PHP is a great language for creating dynamic websites and has a lot of functions to do just about everything on the server side.

Only, with all those functions you need a good error handler. The other languages like perl, c, c# etc. have a try and catch function. As of version 5, this function is also available in PHP. In this post I will try to explain to usage and benefits of try and catch. Ready ?

Example:
Let's say you have a website with some blog posts. Visitors can view the latest post by going to www.example.com/?posts
You also create a page to let visitors read a single post. They'll go to: www.example.com/?posts&item=1
This will tell your script that it needs to get item #1 from the database and display it. Now, as we all know, visitors will try all sorts of things, for example: www.example.com/?posts&item=blablabla. This well tell your script that it should fetch item #blablabla from the database which, ofcourse, does not exist and you get a pretty MySQL error.

Try and Catch
Try and catch works by 'throwing errors'. The script executes a try block and if an error is thrown, the try block will end and the catch function will be executed.

try {
    if (isset($_GET['item'])) {
        $postId = mysql_real_escape_string($_GET['item']);
        $qryPost = "SELECT * FROM posts WHERE id = $postId";

    if (!$rsltPost = mysql_query($qryPost)) {
        Throw new Exception();
    }
    if (!mysql_num_rows($rsltPost)) {
        Throw new Exception();
    }
    $arrPost = mysql_fetch_array($rsltPost);
    echo $arrPost[1];
    }
}
catch (Exception $e) {
    echo "There is no such post!";
}

Try
For starters, all the code that we want to error check, needs to be in the try statement. So we start with:

try {

Next is the code to check whether the URL contains the item variable and if it does, execute the code to display that item. Ofcourse we sanitize the variable before sending it to the database.

if (isset($_GET['item'])) {
    $postId = mysql_real_escape_string($_GET['item']);

Query
Normally I write my queries like this:

$qryPost = mysql_query ("SELECT * FROM Posts WHERE id = $postId") or die (mysql_error());

That works fine for most queries. The downside is that when an error occurs, the script dies and displays an error message which could reveal some of your MySQL configuration to the visitor!
We are going to write our query like this:

$qryPost = "SELECT * FROM posts WHERE id = $postId";

Next we're going to evaluate the query and check if it runs without an error:

if (!$rsltPost = mysql_query($qryPost)) {
        Throw new Exception();
    }

As you see, if the query fails, an error is thrown. this will stop the rest of the try statement from executing and go to the catch statement. The same goes for the second if statement. Only this time it checks if the query returns a row.

Catch
The catch statement is executed when an error is thrown.

catch (Exception $e) {
    echo "There is no such post!";
}

Will only echo "There is no such post!" and the rest of your script/site will continue to function.
The try statement also has some debugging features. You can, for example, get the script line on which the error is thrown, or the exact error message.

This is just a basic example of how to use try and catch. You can read more in the php manual

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Leave a Reply