HomePHP Error Handling in PHP: Introducing Exceptions in PHP 5
Error Handling in PHP: Introducing Exceptions in PHP 5
Welcome to the last part of the series “Error Handling in PHP.” In two parts, this series introduces the basics of error handling in PHP. It demonstrates some of the most common methods for manipulating errors in PHP 4, and explains the implementation of exceptions in PHP 5, particularly in object-oriented environments.
If you spent some time reading the first tutorial of the series, you’ve probably grasped the basic methodologies for handling failures within PHP 4 applications. In that first part, I walked through the use of abrupt “die()” statements, then covered more efficient approaches, such as using “trigger_error()/set_error_handler()” combinations, and finally explained the usage of the popular PEAR_Error object. I tried to illustrate –- at least at a glance -- how different methods can be used to handle potentially conflictive conditions, during the execution of a PHP program.
If you’ve been developing large PHP 4 applications, where very often a centralized error handling mechanism is required, then you may have realized that error manipulating classes can do decent work. However, in PHP 5, things are even better when it comes to handling errors. As you probably know, the latest version of PHP introduces the power and functionality of exceptions, a built-in mechanism for handling program failures through centralized points. This mechanism offers a nice level of flexibility, particularly for delegating error handling to client code and getting detailed information on the errors that occurred and the context within which they happened.
Specifically, this last tutorial will focus on explaining the implementation of exceptions in PHP 5, ranging in from the use of “try-catch” blocks, in addition to subtly more complex structures, such as custom exceptions and exception subclassing. Whether you’re a PHP developer taking the first steps in PHP 5, or a seasoned programmer wanting to fill some gaps in the area of error handling, hopefully this article will be an instructive experience.
Now that you know the topics that will be treated in this article, let’s dive into explaining how PHP 5 exceptions can work for you.