In the previous section I showed you how to utilize the native exception mechanism provided by PHP 5 to handle some errors that might occur when connecting to MySQL, running queries against a selected database, etc. Of course, the simplest way to achieve this was by using a couple of SQL processing classes, whose respective signatures were shown previously.
Nonetheless, since these concepts are pretty simple to grasp, let me go one step further and show you how the aforementioned classes are capable of triggering generic exceptions that can be caught within a typical “try-catch” block.
Having said that, please take a look at the following code sample. It attempts to pull out some records from a sample “USERS” MySQL database table, while this server is turned off:
// connect to MySQL
// fetch data on some users
$result=$db->query('SELECT * FROM users');
// display data on some users
echo 'First Name: '.$row['firstname'].' Last Name: '.$row['lastname'].' Email: '.$row['email'].'<br />';
// turn off MySQL (throws an exception)
/* displays the following
Exception message: Error connecting to the server
Source filename of exception: path/to/file/exception_test.php
Source line of exception: 26
// catch all generic exceptions here
echo 'Exception message: '.$e->getMessage().'<br />';
echo 'Source filename of exception: '.$e->getFile().'<br />';
echo 'Source line of exception: '.$e->getLine();
As you can see, the above hands-on example demonstrates in a nutshell how to use a simple “try-catch” block to intercept any generic exceptions triggered by the pertinent “MySQL” and “Result” classes defined earlier. The situation is in this case particularly illustrative, since the database server has been purposely turned off, which obviously triggers an exception that’s trapped by the corresponding “cacth()” block.
So far, you have seen how to handle generic exceptions by using the base “Exception” class included with PHP 5. As I mentioned in the beginning of this article, however, it’s also possible to extend the functionality of this native class by creating some subclasses from it, and triggering customized exceptions that can be processed by multiple “try-catch()” blocks.
Sounds interesting, doesn’t it? Therefore, in the following section I’m going to modify the respective signatures of the MySQL handling classes that you learned before to provide them with the capacity for triggering not only generic exceptions, but a couple of customized ones.
To learn how this will be done, please click on the link below and keep reading.
blog comments powered by Disqus