Murphy's Law dictates "what can go wrong will." Servers lose electricity, connections time out, paths lead to nothing and hard drives crash. These are things outside of our scripts' control. It is the programmer's job to give scripts a graceful way of handling these and other problems. And let us not forget to mention error handling can help us debug a problem by letting us know there is a problem and where.
My examples are in the PHP4 procedural style--but these concepts can also be done in the Object Oriented style. For example, there is a PEAR_Error class and PHP5 has full support for exceptions and the try/catch structure. Use them if that is an option you want.
Example 1
Error handling when interacting with a database is a common area often overlooked by new programmers. Most new programmers get the connection and selection query, but when fetching results throws an error they have no idea what went wrong. Error handling along the way will tell you EXACTLY where the problem first occurred. A simple example using a MySQL database:
<?php $link = mysql_connect($host, $usr, $pass); // handle connection error if(!$link) { // handle the error – echo to the screen, log it, redirect, whatever // if we are debugging tell me what went wrong // otherwise hide it from malicious users if($debug) { echo 'Error: DB connection '.mysql_error(); } // exit gracefully exit; } ?>
Example 2
What about those that want to do things with their files--read, write, upload or download?
<?php $basepath = '/home/usr/www/downloads/'; switch($_POST['type']) { case 'audio': $type = 'audio/'; break; case 'video': $type = 'vid/'; break; // catch anything default: $type = 'lyric/'; } $path = $basepath.$type.$user.'/'; // handle path error if(!is_dir($path)) { // handle the error – echo to the screen, log it, redirect, whatever // go back to the form or exit gracefully } ?>