Home arrow PHP arrow Page 2 - Error Handling in PHP: Coding Defensively

Killing your scripts: basic error handling with the “die()” statement - PHP

As with any programming language, when you code in PHP, it helps immensely if you set up your applications to handle errors gracefully. This article explores some of the most common error checking methods available in PHP, and provides hands-on examples that use different error handling methods.

TABLE OF CONTENTS:
  1. Error Handling in PHP: Coding Defensively
  2. Killing your scripts: basic error handling with the “die()” statement
  3. Triggering errors: more efficient error handling with the “trigger_error()” function
  4. The PEAR way: looking at the PEAR_Error object
  5. True and false: handling errors with Boolean flags
By: Alejandro Gervasio
Rating: starstarstarstarstar / 52
January 11, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

The first example that implements the basics of script-level error handling is based on the popular “die()” statement. For this reason, I’ll write a simple PHP class, which reads contents from a data file. In its basic incarnation, this class looks like this:

class FileReader{
  var $file;
  var $fileDir='fileDir/';
  function FileReader($file){
    $this->file=$file;
  }
  function getContent(){
    return file_get_contents("{$this->fileDir}{$this->file}.php");
  }
}

 

As I mentioned earlier, the above class implements a trivial file reader. Aside from the constructor, the class exposes only one public method, “getContent()”, which reads the content from a file passed in as an argument to the constructor. As you can see, the class has been coded with no error checking lines, so any object instantiated from it will cause a non-fatal error if the “$file” parameter doesn’t point to a valid file. The lines below show this circumstance:

// instantiate FileReader object
// pass in invalid file to the constructor
$fr=new FileReader('inexistent_file');
// echo file content
echo $fr->getContent();

Warning: file_get_contents(fileDir/.php): failed to open stream: No such file or directory in /path/to/file/exceptions.php on line 4.

Although the example is rather crude, it demonstrates in a nutshell how a class written without any error handler can be easily broken up. Now, in order to implement a basic error handler, I’m going to include some “die()” statements within the class methods, as follows:

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

 

Now, the class looks subtly better and more efficient. Notice how a couple of “die()” statements allow you to code defensively, and introduce an appreciable difference compared to the earlier version. In this case, if I instantiate a new “file reader” object, by pointing it to an inexistent file, this is what I should get as a result:

// instantiate FileReader object
$fr=new FileReader('inexistent_file');
// echo file content
echo $fr->getContent();

File inexistent_file not found.

As you can see, the above snippet is a little more efficient, because it implements a simple error handling mechanism. Instead of leaving out of control conflictive operations, such as reading file contents, the class is capable at least of stopping program execution if an error occurs. Indeed, this is a considerable improvement from a programming point of view, and certainly didn’t demand any hard work from us.

However, pseudo functions like “die()” statements are rather inflexible. After all, it doesn't always happen that a script must be abruptly terminated. Fortunately, PHP exposes other functions which are more helpful and flexible for handling errors. Considering this, let’s move on and have a look at the PHP built-in “trigger_error()” function, in order to find out how it can be used.



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

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 8 - Follow our Sitemap

Dev Shed Tutorial Topics: