Home arrow PHP arrow Page 4 - Error Handling in PHP: Introducing Exceptions in PHP 5

Working with error types: developing an improved error handling mechanism - PHP

Welcome to the last part of the series “Error Handling in PHP.” In two parts, this series introduces the basics of error handling in PHP. It demonstrates some of the most common methods for manipulating errors in PHP 4, and explains the implementation of exceptions in PHP 5, particularly in object-oriented environments.

  1. Error Handling in PHP: Introducing Exceptions in PHP 5
  2. The basics of exceptions: using the “throw” statement and “try-catch” blocks
  3. Obtaining detailed error information: using built-in Exception class’ additional methods
  4. Working with error types: developing an improved error handling mechanism
  5. Exception subclassing: extending the functionality of the built-in Exception class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 43
January 18, 2006

print this article



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;
  public function __construct($file){
      throw new Exception('File '.$file.' not found',self::FILE_DATA_ERROR);
  public function getContent(){
      throw new Exception('Unable to read file
    return $content;
  public function mailContent(){
    if(!@mail('Recipient<user@domain.com>','HTML Page',$this-
      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:

  $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 error occurred when emailing file data, send error message to system logger
  else if($e->getCode()==2){
    echo $e->getMessage().'<br />';

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- 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...

Developer Shed Affiliates


Dev Shed Tutorial Topics: