In this second part of a two-part series on error and exception handling in PHP, we focus specifically on handling exceptions. This article is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
Languages such as Java, C#, and Python have long been heralded for their efficient error-management abilities, accomplished through the use of exception handling. If you have prior experience working with exception handlers, you likely scratch your head when working with any language, PHP included, that doesn’t offer similar capabilities. This sentiment is apparently a common one across the PHP community because, as of version 5, exception-handling capabilities have been incorporated into the language. In this section, you’ll learn all about this feature, including the basic concepts, syntax, and best practices. Because exception handling is new to PHP, you may not have any prior experience incorporating this feature into your applications. Therefore, a general overview is presented regarding the matter. If you’re already familiar with the basic concepts, feel free to skip ahead to the PHP-specific material later in this section.
Why Exception Handling Is Handy
In a perfect world, your program would run like a well-oiled machine, devoid of both internal and user-initiated errors that disrupt the flow of execution. However, programming, like the real world, remains anything but an idyllic dream, and unforeseen events that disrupt the ordinary chain of events happen all the time. In programmer’s lingo, these unexpected events are known as exceptions. Some programming languages have the capability to react gracefully to an exception by locating a code block that can handle the error. This is referred to as throwing the exception. In turn, the error-handling code takes ownership of the exception, or catches it. The advantages to such a strategy are many.
For starters, exception handling essentially brings order to the error-management process through the use of a generalized strategy for not only identifying and reporting application errors, but also specifying what the program should do once an error is encountered. Furthermore, exception-handling syntax promotes the separation of error handlers from the general application logic, resulting in considerably more organized, readable code. Most languages that implement exception handling abstract the process into four steps:
The application attempts something.
If the attempt fails, the exception-handling feature throws an exception.
The assigned handler catches the exception and performs any necessary tasks.
The exception-handling feature cleans up any resources consumed during the attempt.
Almost all languages have borrowed from the C++ language’s handler syntax, known astry/catch. Here’s a simple pseudocode example:
try {
perform some task if something goes wrong throw exception("Something bad happened")
// Catch the thrown exception } catch(exception) { output the exception message }
You can also set up multiple handler blocks, which allows you to account for a variety of errors. You can accomplish this either by using various predefined handlers or by extending one of the predefined handlers, essentially creating your own custom handler. PHP currently only offers a single handler,exception. However, that handler can be extended if necessary. It’s likely that additional default handlers will be made available in future releases. For the purposes of illustration, let’s build on the previous pseudocode example, using contrived handler classes to manage I/O and division-related errors:
try {
perform some task if something goes wrong throw IOexception("Could not open file.") if something else goes wrong throw Numberexception("Division by zero not allowed.")
If you’re new to exceptions, such a syntactical error-handling standard seems like a breath of fresh air. The next section applies these concepts to PHP by introducing and demonstrating the variety of new exception-handling procedures made available in version 5.