Advertisement
Achilles

Simple example to understand try and catch

Jul 19th, 2013
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.99 KB | None | 0 0
  1. <?php
  2.  
  3.     class EmptyName extends Exception
  4.     {
  5.         private $_nameError;
  6.        
  7.         public function __construct( $message )
  8.         {
  9.             $this->_nameError = $message;
  10.         }
  11.        
  12.         public function getNameError()
  13.         {
  14.             return $this->_nameError;
  15.         }
  16.     }
  17.    
  18.     class EmptyEmail extends Exception
  19.     {
  20.         private $_emailError;
  21.        
  22.         public function __construct( $message )
  23.         {
  24.             $this->_emailError = $message ;
  25.         }
  26.        
  27.         public function getEmailError()
  28.         {
  29.             return $this->_emailError;
  30.         }
  31.     }
  32.  
  33.     $name = "someone";
  34.     $email = "";
  35.    
  36.     try
  37.     {
  38.         if( empty( $name ) )
  39.         {
  40.             throw new EmptyName( "Error name must not be empty" );
  41.         }
  42.        
  43.         if( empty( $email ) )
  44.         {
  45.             throw new EmptyEmail( "Error email must not be empty" );
  46.         }
  47.        
  48.         else
  49.         {
  50.             echo "Name : $name" . "<br>" ."Email : $email";
  51.         }
  52.     }
  53.    
  54.     catch( EmptyName $e )
  55.     {
  56.         echo $e->getNameError();
  57.     }
  58.    
  59.     catch ( EmptyEmail $e )
  60.     {
  61.         echo $e->getEmailError();
  62.     }
  63.    
  64.     catch ( Exception $e )
  65.     {
  66.         echo $e->getMessage();
  67.     }
  68.  
  69. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement