Create your own Custom Exceptions

Here’s a nice tip about creating your own custom Exceptions very easily by extending the standard Exception class:

PHP Code:
class fileException extends Exception {}

This is very handy when you want to do a bunch of stuff in one go and handle the exceptions centrally but not in exactly the same way.

Suppose that you want to read a value from a file just before you do the query and you’ve created a method to do this:

PHP Code:
function readFile($sFileName) {
if (!file_exists($sFileName) {
throw new fileException('Sorry, the file could not be found.');
} if (!is_readable($sFileName) {
throw new fileException('Hmm, the file is not readable.');
// read from file ...

Now you can:

PHP Code:
try {
// try to read from the file
$value = readFile('somefile.log');

// try to query db
$res = mysql_query("UPDATE .... WHERE something='$value’");
} catch (fileException $e) {
// now you can easily send a mail to the admin to tell him to create the file or similar
echo $e->getMessage();
} catch (Exception $e) {
// and over here you can email yourself to fix the db connection
echo $e->getMessage();
// while to the user it all looks the same

This example doesn’t make a whole lot of sense in the real world but I hope you get the idea.
It’s very handy if you need to send error-messages to different people or if the flow of an application should go in different directions, depending on the exception.