CopyPastehas never been so tasty!

Custom Exception Class in PHP

by anonymous

  • 0
  • 0
  • 0
70 views

Orignal Source:http://codingvilla.com/custom-exception-class-php-single-article-581.aspx

Custom Exception Class:

 

Custom exception class is class that make according to your requirements. You can customize the exception class according to your need.

 

Custom Exception Class in PHP:

 

To make a custom exception class in php is very simple.We make a special exception class that hold the function of exception that can be called when expection occurs. This special class inherits the php exception class properties and youc can add custom function in it. In the given code we create a custom Exception class that extends the php exception class properties, and make a custom function email validation that returns an error message if email is invalid.

 

 

Code:

 

 

<?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($email, FILTER_VALIDATE_EMAIL) === FALSE)

    {

    //throw exception if email is not valid

    throw new customException($email);

    }

  }

catch (customException $e)

  {

  //display custom message

  echo $e->errorMessage();

  }

?>

 

 

Above is a simple code to make a custom exception class in php.

 

This simple article tells that how we can create a custom exception class in php.

 

Add A Comment: