PHP
  Home arrow PHP arrow Page 4 - 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 - 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


       · 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 6 hosted by Hostway
    Stay green...Green IT