CHAPTER 7 – EXCEPTIONS

What Are Exceptions?

Exceptions are a high-level built-in error mechanism that is new as of PHP 5. Just as for PEAR errors, the relative cost of generating exceptions is high, so use them only to notify about unexpected events. Exceptions are objects that you can "throw" to PHP. If something is ready to "catch" your exception, it is handled gracefully. If nothing catches your exception, PHP bails out with an error message like this: Fatal error: Uncaught exception 'FileException' with message 'Could not open config /home/ssb/foo/conf/my.conf' in .../My/Config.php:49 Stack trace: #0 .../My/Config.php(31): config->parseFile('my.conf') #1 .../My/prepend.inc(61): config->__construct('my.conf') #2 {main} thrown in .../My/Config.php on line 49 Although PEAR errors are loosely modeled after exceptions, they lack the execution control that exceptions provide. With PEAR errors, you always need to check if a return value is an error object, or the error does not propagate down to the original caller. With exceptions, only code that cares about a par- ticular exception needs to check for (catch) exceptions.

Post Comment
Login to post comments