Replacing Errors with Exceptions

Before you create your derived class, let's look at the code that the MySQLException class will replace. The MySQLConnect class constructor provides a good example of how your exception class will be used.

Recall that your main goal when creating your own exception class is to rid your code of messy error trapping procedures. You've achieved this to some extent simply by incorporating error trapping into class methods, but you can reap further benefits.

In Listing 10-2, exceptions will replace the code that currently calls the die function. In the first case you ❶ terminate the program because mysql_connect cannot create a connection, whether because of an incorrect host, username, or password, or perhaps because the MySQL server is down. In any case, a look at the built-in error messages will help identify the problem and whether or not it is within your control.

Listing 10-2. Code of MySQLConnect class constructor that calls the die function
function __construct($hostname, $username, $password){
    if(MySQLConnect::$instances == 0){
        $this->connection = mysql_connect($hostname, $username, $password) or
        ❶die(mysql_error(). " Error no: ".mysql_errno());
        MySQLConnect::$instances = 0;
    }else{
        $msg = "Close the existing instance of the ".
            "MySQLConnect class.";
        ❷die($msg);
    }
}

In the second case ❷ execution is deliberately terminated because your class is being misused. You don't want a client programmer to attempt to open two connections simultaneously because one is all that's required. Here, you have two different kinds of errors, one of indeterminate cause and the other an instance of class misuse.


Note:

Recall that because PHP is not a compiled language there is no such thing as a compile-time error. By creating your own exception class you partially remedy this situation by creating messages that indicate class misuse.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.78.106