PHP 5 Exception Handling

April 26th, 2006

PHP has some really sweet new features and one of them is the ability to throw and catch exceptions.

When I was browsing Sitepoint I read a post saying that the only thing they need to do is get rid of the class-”hinting” in the catch clause. I guess they didn’t get the point of extending the base Exception class.

I’ve found extending the Exception class useful when reporting the errors back from a Database connection object. Basically I wanted to return a message array to describe the problem in English, then with additional messages from MySQL. This is really just so I can separate HTML from the PHP, for instance I could just return “Could not connect to database: ” . mysql_error() and be done with it, but if a design changes and strong isn’t applicable or something, it’s not that much good. Ok, so perhaps I’m just being anally-retentive but it’s cool to demonstrate anyway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class DatabaseException extends Exception
{
  private $error;	
 
  function __construct($error)
  {
    $this->error = $error;
  }
 
  function getMessageArray()
  {
    return $this->error;
  }
 
}

[1] Yup, you use either “public” “private” or “protected” when declaring variables now. Unfortunately they’re not C++ style–so you have to use them for each variable. [5] Also you use __construct for constructors.

Next the simple database class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Database
{
  private $host;
  private $password;
  private $user;
  private $database;
  public $connection_tracker;
 
  function __construct($host, $user, $password, $database)
  {
    $this->host = $host;
    $this->password = $password;
    $this->user = $user;
    $this->database = $database;
    $this->connect();
  }
 
  function connect()
  {
    if (!$this->connection_tracker = @mysql_connect($this->host, $this->user, $this->password))
    {
      $error_array =  array (
      "message" => "Could not connect to MySQL daemon",
      "database_reports" => mysql_error()
      );
 
      throw new DatabaseException($error_array);
    }
  }
}

1
2
3
4
5
6
7
8
9
10
11
try
{
  $Database = new Database('localhost', 'rot', 'discovery', 'table'); 
}
 
catch (DatabaseException $e)
{
  $error_messages = $e->getMessageArray();
  echo $error_messages['message'];
  echo $error_messages['database_reports'];
}

Now you can put the HTML around it as required by the design.

One Response to “PHP 5 Exception Handling”

  1. SimpleXML — is it faster the the regular XML libraries? » chuyskywlk Says:
    April 27th, 2006 at 1:30 am

    […] Help.com Tag: simplexml

    Help.com Tag: benchmarks

    PHP 5 Exception Handling

    Why PR […]