Good programmers must always ensure that all possible scenarios are taken into account. Consider a scenario in which your site offers an HTML form from which the user could subscribe to a newsletter by submitting his or her e-mail address. Several outcomes are possible. For example, the user could do one of the following:
Proper exception handling will account for all such scenarios. However, you need to provide a means for catching each exception. Thankfully, this is easily possible with PHP. Listing 8-3 shows the code that satisfies this requirement. Listing 8-3. Catching Multiple Exceptions <?php
/* The Invalid_Email_Exception class is responsible for notifying the site class Invalid_Email_Exception extends Exception { function __construct($message, $email) { private function notifyAdmin($email) { } /* The Subscribe class is responsible for validating an e-mail address class Subscribe { function validateEmail($email) { try { if ($email == "") { list($user,$domain) = explode("@", $email); if (! checkdnsrr($domain, "MX")) else } /* This method would presumably add the user's e-mail address to function subscribeUser() { } #end Subscribe class /* Assume that the e-mail address came from a subscription form. */ $_POST['email'] = "someuser@example.com"; /* Attempt to validate and add address to database. */ ?> You can see that it’s possible for two different exceptions to fire, one derived from the base class and one extended from the Invalid_Email_Exceptionclass. Summary The topics covered in this chapter touch upon many of the core error-handling practices used in today’s programming industry. While the implementation of such features unfortunately remains more preference than policy, the introduction of capabilities such as logging and error handling has contributed substantially to the ability of programmers to detect and respond to otherwise unforeseen problems in their code. In the next chapter we take an in-depth look at PHP’s string-parsing capabilities, covering the language’s powerful regular expression features, and offering insight into many of the powerful string-manipulation functions.
blog comments powered by Disqus |
|
|
|
|
|
|
|