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

The basics of exceptions: using the “throw” statement and “try-catch” blocks - 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



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){
      throw new Exception('File '.$file.' not found');
  public function getContent(){
      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:

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

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

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: