Sunday, May 29, 2011

Exceptions Defined - Errors vs Exceptions in PHP

Continued From Here

An EXCEPTION is also a PHP fatal ERROR which similarly, halts the entire program when encountered. However, it is meant to be thrown for exceptional conditions only, that the PHP engine itself cannot control. These are mostly WIRING issues and/or PROGRAM ERRORS with external resources and elements i.e file permissions, connection to database management systems and other external I/O that PHP has little or nothing to do about and expects them to be simply working all the time.

The same assumption that resource or element should always be working is also true in reverse. That a fatal error or an EXCEPTION, either coming from a wiring error or program error, associated with an external resource or element, can or will also happen anytime. It is because of this "exceptional" condition that it can either be working and not working which PHP has nothing to do or can do nothing about implicitly that we call such occurrences as EXCEPTIONS. It is therefore logically correct that when an EXCEPTION is encountered, it should then be catchable and handled so that an alternative code can be run (i.e retry a connection attempt). The try-catch block is specifically meant/built for that reason.

try {
    $db->connect();
} catch (Exception $e) {
    //do something when an exception is encountered. i.e retry.
}

For the convenience of the PHP developer, PHP gives the ability to throw a user-defined exception so he can throw an EXCEPTION for errors that he deems "exceptional" and errors he deems catchable with an alternative code snippet to run. With good design and usage, you can centrally manage your error handler. Please bear in mind though, that in the hands of the unwary, a program can end-up hiding a lot of errors or flow if the alternative code or catch block doesn't trigger any error, in any form and simply continue. You have been warned. See example below.

//bad code
try {
    //The method fetch throws a user-defined Exception. The error (which is thrown as an Exception), whatever it is, will be very hard to debug and it becomes harder as the code grows.
    $res = $db->fetch();
} catch (Exception $e) {
    $res = array('test_data');
}


//better code
try {
    //The method fetch throws a user-defined Exception. The error (which is thrown as an Exception), whatever it is, will be very hard to debug and it becomes harder as the code grows.
    $res = $db->fetch();
} catch (Exception $e) {
    //Send a warning or error code first, before proceeding
    trigger_error("Error encountered, using test data - " . $e->getMessage(), E_USER_WARNING);
    $res = array('test_data');
}
  • Related Links Widget for Blogspot

No comments: