Exception handling

Exception handling


Posted in : PHP Posted on : January 10, 2011 at 5:56 PM Comments : [ 0 ]

This section contains the detail about Exception handling in PHP.

Exception handling

Exception handling is the handling of the specific error. It changes the flow of the code when exception or these specific errors occurred.

When exception occurred, the current state is saved and it switch to the exception handler. After it, following are the possibilities:

  • handler can terminate execution after this, or
  • it may resume the execution from the saved code state, or
  • switch to new location for further execution.

In PHP, we have try, throw & catch for exception.

try : The code or function on which you have doubt that it may throw exception, should be placed in  try block. If it will not have the exception, it will execute normally.

catch : A catch block catch the exception and creates an object containing the exception information.

throw : It is used to trigger an exception.

Given below example will give you a clear idea :

<?php
//throwing excepetion inside a method
function Test($count)
{
if($count<5)
{
throw new Exception("Value must be above 5");
}
return true;
}

//exception triggering inside a "try" block
try
{
Test(3);
echo 'Number is above 5';
}

//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>

Output :

The above code will throw an exception and following message will display :

Message: Value must be above 5

Creating your own custom exception

In PHP, you can create your own custom exception by extending 'Exception' class. This way you can add custom function to it.

Given below example will give you a clear idea.

<?php
class customException extends Exception
{
public function displayError()
{
//error message
$MsgErr= '<b>Custom message </b>: Error on line '.$this->getLine().' in '.$this->getFile()
.'<b>'.$this->getMessage();
return $MsgErr;
}
}
//throw excepetion inside a method
function Test($count)
{
if($count<5)
{
return true;
}

}

try
{
//check if
if(Test(3))
{
//throwing custom exception
throw new customException();
}
}

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

Output :

Custom message : Error on line 28 in C:\wamp\www\etc\customException.php

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics