Pages

Friday, June 22, 2012

PHP Exception Handling

An exception can be thrown, and caught ("catched") within PHP.
 Code may be surrounded in a try block, to facilitate the catching of potential exceptions.
Each try must have at least one corresponding catch block.
Multiple catch blocks can be used to catch different classes of exceptions.
Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present)
will continue after that last catch block defined in sequence.

Exceptions can be thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed,
and PHP will attempt to find the first matching catch block.
If an exception is not caught, a PHP Fatal Error will be issued
With an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

The following is an example of a re-thrown exception and the using of getPrevious function:

<?php



$name = "Name";



//check if the name contains only letters, and does not contain the word name



try

   {

    try

       {  

          if (preg_match('/[^a-z]/i', $name))

            {

              throw new Exception("$name contains character other than a-z A-Z");

            }  

          if(strpos(strtolower($name), 'name') !== FALSE)

           {

              throw new Exception("$name contains the word name");

           }

       echo "The Name is valid";

     }

     catch(Exception $e)

      {

        throw new Exception("insert name again",0,$e);

      }

   }



catch (Exception $e)

   {

   if ($e->getPrevious())

   {

    echo "The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";

   }

   echo "The Exception is: ".$e->getMessage()."<br/>";

   }

 ?>

No comments:

Post a Comment