HomePHP Intercepting Customized Exceptions in PHP 5
Intercepting Customized Exceptions in PHP 5
Welcome to the second part of a four-part series on sub classing exceptions in PHP 5. In the first part of this series, you learned how to build a basic processing class which could throw customized exceptions to client code. What you haven't yet learned, however, is how to build the code to catch these exceptions. That is the topic of this article.
As you probably know, one of the most relevant improvements incorporated into the object model of PHP 5 is the capacity for triggering and intercepting exceptions by way of conventional "try-catch" blocks. This feature facilitates the handling of different error conditions via a compact, highly-centralized mechanism.
While the built-in exception system that comes bundled natively with PHP 5 is usually good enough to handle errors and other critical conditions during the execution of a given web application, it's worthwhile to mention that there are a number of additional cases where it is necessary to implement an exceptions system that can handle different failures in a more specific way.
That's precisely where exception subclasses come in. It's possible to derive a few different child classes from the base "Exception" built-in class, which allows us to build specific exception handling modules within a single PHP 5-driven application.
Of course, if you already read the introductory article of this series, then hopefully you'll be familiar with building classes that are capable of triggering customized exceptions in the context of a concrete PHP 5 application. As you'll certainly recall, in the course of that tutorial, I demonstrated how to define a basic MySQL-processing class which could throw MySQL-related exceptions to client code, instead of using only generic ones.
Indeed, building a class like the one described above is a straightforward process that doesn't require you to have the sharpest skills for using the object-oriented parading with PHP 5. This only gives us half of the picture, however, since it's also necessary to implement an exception mechanism that is capable of catching these customized, MySQL-related exceptions via a conventional "try-catch" block.
The mechanism in question can be quickly constructed by deriving a subclass from the parent "Exception" that comes included with PHP 5. Therefore, in the next few lines I'm going to teach you how perform this process in an approachable fashion, so you can start incorporating exception sub classes into your own PHP 5 applications in very short time. Let's begin now!