PHP Exceptions (Cont.)


Basic Use of Exceptions (Cont.)
The code below checks whether the HTTP host is located at the CEM, whose URL includes the string “undcemcs01.und.edu .” It throws an exception and catches it:
  1. The checkHost function is created. It checks if the HTTP host is located at undcemcs01.und.edu, for example. If it is not, an exception is thrown.

  2. The checkHost function is called in a “try” block. The HTTP host is found by using the PHP variable $_SERVER.

  3. The exception within the checkHost function is thrown.

  4. The “catch” block retrieves the exception and creates an object ($e) containing the exception information

  5. The error message from the exception is echoed by calling $e->getMessage from the exception object.

  6. The string function strstr(string,search) searches for the first occurrence of a string inside another string.
 <html><body>
 <?php
   // Create function with an exception.
   function  checkHost( $host ) {
     if ( strstr( $host, "" ) == false )
       throw new Exception( "The HTTP host $host is not at the NDUS!" );
     return true;
   }
   // Trigger exception in a "try" block
   try {
     $index = "";
     checkHost( $_SERVER[$index] );
     // If the exception is thrown, this text will not be shown.
     echo  "The HTTP host is " . $_SERVER[$index];
   }
   // Catch exception.
   catch ( Exception $e ) {
     echo  "Message: " . $e->getMessage( );
   }
 ?>
 </body></html>
       




      New York is an exciting town where something is happening    
      all the time, most of it unsolved.    
      — Johnny Carson