Home arrow PHP arrow Exception Handling in PHP

Exception Handling in PHP

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).

TABLE OF CONTENTS:
  1. Exception Handling in PHP
  2. PHP’s Exception-Handling Implementation
  3. Methods
  4. Extending the Exception Class
  5. Catching Multiple Exceptions
By: Apress Publishing
Rating: starstarstarstarstar / 2
January 04, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Exception Handling 

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:

  1. The application attempts something.
  2. If the attempt fails, the exception-handling feature throws an exception. 
     
  3. The assigned handler catches the exception and performs any necessary tasks. 
     
  4. 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.")

// Catch IOexception
} catch(IOexception) {
    output the IOexception message
}

// Catch Numberexception
} catch(Numberexception) {
    output the Numberexception message
}

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.



 
 
>>> More PHP Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
   

PHP ARTICLES

- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap

Dev Shed Tutorial Topics: