While most of the excitement surrounding the release of PHP 5 focused on its XML and object-oriented features, the Standard PHP Library (SPL) also saw some significant improvements that went mostly unnoticed. In the first of two articles covering the SPL, David Fells discusses the Exception class, which lets programs handle errors more gracefully and simplifies debugging.
Amid all the noise and excitement surrounding the release of PHP and its shiny new XML and object oriented features, the Standard PHP Library (SPL) slipped by without much recognition. Exception handling has been a major feature add for PHP 5, and the classes built into PHP are a part of the SPL. This article will demonstrate basic application of several SPL classes and provide information on the classes and interfaces available to PHP 5 programmers.
This article is the first part in a series discussing the classes available in the SPL and their uses. In this article we will discuss the Exception class and its application. Exceptions serve a dual purpose - they allow applications to gracefully handle errors, and they allow simplification of the debugging process, which adds up to a more efficient development process and less stress for developers.
Exceptions have been around for quite a while in languages like C++ and Java, but simple scripting languages have never had support for this graceful error handling device. That changed with the release of PHP 5. Exceptions are not all that special as far as objects go; they are essentially containers for error information. The interesting part is how exceptions are created and identifed. To use exceptions, one only needs to be familiar with the special control structures and functions associated with them. They are built-in and require no configuration and only a handful of brain cells. Exception handling requires proper use of "try"/"catch" blocks and the use of the "throw()" function.
Exceptions are created, or thrown, in one of two ways. Either a developer tells the application to throw an exception when a specific error condition is met (such as data out of the expected range as a function parameter) or the language itself throws an exception when it encounters an application error. The latter type are generated from a lower level in terms of system architecture, but the end result is the same: developers can catch exceptions that are thrown by application code and either ignore them, attempt to recover or gracefully fail. Any option is better than creating a web of error handling methods (such as the PEAR Error class) or by using "die()", but exceptions are, pun intended, an exceptional solution to the problem of graceful, clean error handling.