<?php
/* Creating Custom Exception Class */ 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; } } /* Creating Custom Exception Class */ $email = "[email protected]"; try { //check if if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) { //throw exception if email is not valid throw new customException($email); } echo "Email Id is Valid"; } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>
0 Comments
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.
This is what normally happens when an exception is triggered:
<?php
/* Function to Throw an Exception */ function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } /* Function to Throw an Exception */ //trigger exception in a "try" block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; } catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?>
|