PHP
  Home arrow PHP arrow Page 4 - Error Handling in PHP: Introducing Exceptions in PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

Error Handling in PHP: Introducing Exceptions in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 39
    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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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 - Working with error types: developing an improved error handling mechanism
    ( Page 4 of 5 )

    In order to build an improved error handler, I’ll use a slightly modified version of the sample class, which passes the number of errors generated to the constructor of the Exception class. Take a look at its definition:

    class FileReader{
      private $file;
      private $fileDir='fileDir/';
      const FILE_DATA_ERROR=1;
      const EMAIL_DATA_ERROR=2;
      public function __construct($file){
        if(!file_exists("{$this->fileDir}{$file}.php")){
          throw new Exception('File '.$file.' not found',self::FILE_DATA_ERROR);
        }
        $this->file=$file;
      }
      public function getContent(){
        if(!$content=file_get_contents("{$this->fileDir}{$this-
    >file}.php")){
          throw new Exception('Unable to read file
    contents',self::FILE_DATA_ERROR);
        }
        return $content;
      }
      public function mailContent(){
        if(!@mail('Recipient<user@domain.com>','HTML Page',$this-
    >getContent())){
          throw new Exception('Unable to send by email file contents',self::EMAIL_DATA_ERROR);
        }
      }
    }

    As you can see in the above example, I’ve rewritten the sample class, so it can throw different exceptions when things go wrong. I’ve added a new class method for sending the contents of the sample file by email. This means that each time an exception is thrown, the class will pass an error message to the Exception class, along with the type of error generated.

    This is possible because the built-in Exception class accepts two parameters: the error message and the error code. So, returning to the example, I’ve defined two constants, in order to identify when the error is caused, when manipulating file contents or when emailing file data. According to the new definition for the sample class, the improved error handler might be implemented as follows:

    try{
      $fr=new FileReader('sample_file'); // potential error condition
      // email file content
      $fr->mailContent(); // potential error condition
      // echo file content
      echo $fr->getContent(); // potential error condition
    }
    catch(Exception $e){
      // if error occurred when reading file data, stop program execution
      if($e->getCode()==1){
        die($e->getMessage());
      }
      // if error occurred when emailing file data, send error message to system logger
      else if($e->getCode()==2){
        echo $e->getMessage().'<br />';
        error_log($e->getMessage(),0);
      }
    }

    If you study the above snippet, then you’ll probably understand what’s going on. Within the “catch” block, the error code is checked, in order to determine the type of raised error. According to this value, different courses of action will be taken. If a failure occurred when dealing with file contents, a message error is displayed and the program is simply halted. On the other hand, if the error was triggered when emailing file contents, the script will show the corresponding error message, and attempt to store the message in the system logger (if possible).

    Now, with the introduction of a few modifications to the original sample class, I’ve set up a more efficient error handler, which can react differently, based on the second error parameter passed to client code. Certainly, it’s possible to use all the methods of the Exception class shown above, and develop an error handing mechanism capable of giving detailed information on the failure and its context.

    Having demonstrated how to develop a more efficient error handler, the next step consists of writing a new example, this time using custom exceptions (also known as exception subclassing). These can be extremely helpful, particularly when it’s necessary to extend the functionality of the PHP built-in Exception class. Want to find out how this is done? All right, keep on reading.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek