Home arrow PHP arrow Page 5 - Exception Handling in PHP

Catching Multiple Exceptions - PHP

In this second part of a two-part series on error and exception handling in PHP, we focus specifically on handling exceptions. This article is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).

TABLE OF CONTENTS:
  1. Exception Handling in PHP
  2. PHP’s Exception-Handling Implementation
  3. Methods
  4. Extending the Exception Class
  5. Catching Multiple Exceptions
By: Apress Publishing
Rating: starstarstarstarstar / 2
January 04, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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:

  1. Provide a valid e-mail address 
     
  2. Provide an invalid e-mail address 
     
  3. Neglect to enter any e-mail address at all 
     
  4. Attempt to mount an attack such as a SQL injection

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
       administrator in the case that the e-mail is deemed invalid. */

    class Invalid_Email_Exception extends Exception {

       function __construct($message, $email) {
         
$this->message = $message;
         
$this->notifyAdmin($email);
       }

       private function notifyAdmin($email) {
          mail("admin@example.org","INVALID EMAIL",$email,"From:web@example.com");
       }

    }

    /* The Subscribe class is responsible for validating an e-mail address
       and adding the user e-mail address to the database. */

    class Subscribe {

        function validateEmail($email) {

           try {

               if ($email == "") {
                   throw new Exception("You must enter an e-mail address!");
               } else {

                  list($user,$domain) = explode("@", $email);

                  if (! checkdnsrr($domain, "MX"))
                      throw new Invalid_Email_Exception(
                          "Invalid e-mail address!", $email);

                  else
                      return 1;
               }
           } catch (Exception $e) {
                 echo $e->getMessage();
           } catch (Invalid_Email_Exception $e) {
                 echo $e->getMessage();
           }

        }

        /* This method would presumably add the user's e-mail address to
           a database. */

        function subscribeUser() {
            echo $this->email." added to the database!";
        }

    } #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. */
   
if (isset($_POST['email'])) {
       
$subscribe = new Subscribe();
       
if($subscribe->validateEmail($_POST['email']))
           
$subscribe->subscribeUser($_POST['email']);
    }

?>

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.



 
 
>>> More PHP Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- 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: