Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^34) CHAPTER 4 ■ EXCEPTIONS
When thrown, this exception generates the following message:
Could not connect to the database
First, the code in Listing 4-1 creates a function that has a potential for failure. If the data-
base is inaccessible, the connection function will return false, and an exception is thrown. The
throw keyword is used with an Exception class object and tells the application when an error
has occurred. Once an exception is thrown, instead of completing the function, the execution
jumps to the catch block, where the application is told to echo the error message.


Extending Exceptions.


Nonspecialized exceptions are great, but exceptions can be so much better. In Listing 4-1, it
would be much more useful if you could examine why the database connection failed. To be
able to get this information, you need to integrate Exception with the appropriate function. For
example, pg_last_error() provides the reason for a PostgreSQL error.
Listing 4-2 demonstrates how to create a custom exception to use when connecting to a
PostgreSQL database.

Listing 4-2. Creating a Custom Exception Class

class DatabaseException extends Exception {

protected $databaseErrorMessage;

public function __construct($message=null, $code = 0) {
$this->databaseErrorMessage = pg_last_error();
parent::__construct($message, $code);
}

protected function getDatabaseErrorMessage() {
return $this->databaseErrorMessage;
}

}

This code defines a DatabaseException class that extends from Exception and that declares a
new method. This method will record the pg_last_error() in context and expose it for later access.
When creating this class, you must be careful to call the base class’s constructor, as failing
to do this can result in unreliable and often unstable behavior within PHP.
Listing 4-3 shows how to use this new exception.

McArthur_819-9C04.fm Page 34 Friday, February 1, 2008 10:25 AM

Free download pdf