In the prior section, you hopefully learned how to derive a basic subclass from the built-in "Exception" class bundled with PHP 5 to create a customized exception mechanism that permits you to intercept all of the exceptions triggered by the sample "MySQL" class defined previously.
So now it's time to set up an example to demonstrate the real functionality of the exception mechanism. Please study the following code sample, which shows how to handle generic and MySQL-related exceptions by using a couple of "catch()" blocks. Here it is:
// 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 a MySQL exception)
/* displays the following
Catching MySQL exceptions...
Exception message: Error connecting to the server
Source filename of exception: path/to/file/exception_test.php
Source line of exception: 36
// catch MySQL exceptions here
// catch default exceptions here
echo 'Catching default exceptions...<br />';
echo 'Exception message: '.$e->getMessage().'<br />';
echo 'Source filename of exception: '.$e->getFile().'<br />';
echo 'Source line of exception: '.$e->getLine();
As shown by the above hands-on example, each time the pertinent "MySQL" abstraction class throws an exception of type "MySQLException," it will be neatly caught by the first "catch()" block and processed in a pretty trivial manner. On the other hand, all of the generic exceptions will be intercepted by the second block, in this way demonstrating how simple it is to develop a customized exception mechanism with PHP 5 by means of simple inheritance. Simple and nice, right?
Finally, I recommend that you play with all of the code samples included in this tutorial, so you can grasp more quickly how to take advantage of using exception subclasses in PHP 5-controlled applications.
In this second chapter of the series, you hopefully learned how to combine a MySQL abstraction class along with a subclass derived from the built-in "Exception" parent, in order to implement a customized exception system with PHP 5. As you saw previously, this process is actually a no-brainer and can be mastered in a very short time.
You should notice, however, that all of the tasks aimed at processing MySQL result sets were handled specifically by a "Result" class. Bearing in mind this concept, in the next tutorial I'm going to teach you how to modify the signature of this particular class to provide it with the capacity for throwing data set-related exceptions.
Want to learn how this will be done? Don't miss the next part!
blog comments powered by Disqus