News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

Creating a Custom Classs Exception in PHP

Started by thiruvasagamani, Aug 15, 2008, 07:49 PM

Previous topic - Next topic

thiruvasagamani

Creating a Custom Exception Class

Creating a custom exception handler is quite simple. We simply create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.

The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it.

Lets create an exception class:

<?php
class customException extends Exception
 
{
 public function 
errorMessage()
  {
  
//error message
  
$errorMsg 'Error on line '.$this->getLine().' in '.$this->getFile()
  .
': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
  return 
$errorMsg;
  }
 }

$email "someone@example...com";

try
 {
 
//check if 
 
if(filter_var($emailFILTER_VALIDATE_EMAIL) === FALSE)
  {
  
//throw exception if email is not valid
  
throw new customException($email);
  }
 }

catch (
customException $e)
 {
 
//display custom message
 
echo $e->errorMessage();
 }
?>


The new class is a copy of the old exception class with an addition of the errorMessage() function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine() and getFile() and getMessage().
Example explained:

The code above throws an exception and catches it with a custom exception class:

   1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
   2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
   3. The $email variable is set to a string that is not a valid e-mail address
   4. The "try" block is executed and an exception is thrown since the e-mail address is invalid
   5. The "catch" block catches the exception and displays the error message
Thiruvasakamani Karnan