PHP
  Home arrow PHP arrow Page 2 - Error Handling in PHP: Introducing Exc...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Error Handling in PHP: Introducing Exceptions in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 31
    2006-01-18

    Table of Contents:
  • Error Handling in PHP: Introducing Exceptions in PHP 5
  • The basics of exceptions: using the “throw” statement and “try-catch” blocks
  • Obtaining detailed error information: using built-in Exception class’ additional methods
  • Working with error types: developing an improved error handling mechanism
  • Exception subclassing: extending the functionality of the built-in Exception class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Error Handling in PHP: Introducing Exceptions in PHP 5 - The basics of exceptions: using the “throw” statement and “try-catch” blocks


    (Page 2 of 5 )

    At a basic level, PHP 5 exposes the classic “throw” statement and the “try-catch” blocks for implementing exceptions. As expected, any exception can be “thrown” in sections of an application, and trapped within the corresponding “catch” block. While this combination may seem trivial, it really provides a robust error management mechanism. First of all, it allows you to delegate error handling to client code; second, it provides useful and detailed information about the program failure; and finally it supports handling multiple errors conditions, by allowing you to separate program flow from error managing routines.

    In order to illustrate a basic implementation of exceptions, let’s see the first example, which uses the “FileReader” class that you saw in the first article:

    class FileReader{
      private $file;
      private $fileDir='fileDir/';
      public function __construct($file){
        if(!file_exists("{$this->fileDir}{$file}.php")){
          throw new Exception('File '.$file.' not found');
        }
        $this->file=$file;
      }
      public function getContent(){
        if(!$content=file_get_contents("{$this->fileDir}{$this-
    >file}.php")){
          throw new Exception('Unable to read file contents');
        }
        return $content;
      }
    }

    In this case, the above class throws a new exception when something goes wrong. As you can see, I’ve coded the class in a defensive way, so whether an error occurs when the sample file isn’t found or when reading file contents, an exception is properly thrown. At first glance, you can appreciate the benefits of using exceptions, since the flow of class operations is kept under normal conditions, and its methods aren’t responsible for handling failures that might eventually arise. Now, let’s see how a “try-catch” block can be used, in order to trap the exceptions thrown by a “FileReader” object. The example is as follows:

    try{
      $fr=new FileReader('sample_file'); // potential error condition
      // echo file content
      echo $fr->getContent(); // potential error condition
    }
    catch(Exception $e){
      echo $e->getMessage();
      exit();
    }

    As shown above, object instantiation, together with method calls, are wrapped up into a single “try” block, so eventual exceptions thrown by the class will be caught within the appropriate “catch” block. In this particular example, I’ve instructed the “catch” block to stop program execution after displaying the error message passed as an argument to the constructor of the exception object. The line below:

    echo $e->getMessage();

    uses the “getMessage()” method to show the corresponding error message. By default, the PHP 5 interpreter will trigger a fatal error if the file to be read isn’t found, but this condition can be handled in a different way, by altering only the logic implemented within the pertinent “catch” block.

    As you can see, the given example doesn’t provide much information on the error itself or its context. Fortunately, the built-in PHP Exception class exposes a few useful methods, which can be used to obtain detailed data when a program failure happens. Keeping that in mind, I’ll build up another example, so you can see how other exception methods are used, in order to obtain more specific information on raised errors.

    More PHP Articles
    More By Alejandro Gervasio


       · This last installment of the series explores specifically error handling in PHP 5....
       · thank you very much for your nice article, especially for the exception part.just...
       · Thank you so much for your comments about my PHP exceptions-related tutorial.If you...
       · What I mean is that:catch(Exception $e){ // if error occurred when reading...
       · Thank you again for your comments. Now that you clarified your point, it's clear to...
       · Nice Description. Thanks a lot for explaining
       · Thank you for the kind comments on my PHP article, and I'm glad to know it was...
       · Hey Alejandro, I just wanted to thank you so much for writing this article as well...
       · Thank you for the kind words on my PHP article. Simply I didn’t use constants in...
       · Hi Haret,Thank you for the compliments on my PHP article. I really appreciate...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway
    Stay green...Green IT