Exception handling

Exception handling in PHP

Exception handling

An exception is an event that occurs at time of execution of program / script that interrupt the execution of the program. PHP 5 introduce the mechanism of exception that handle the error condition in case of object.

 php exception handling

PHP 5 has the exception model similar to the other object oriented programming languages and provide three keywords to handle the exception

  • Try
  • Catch
  • Throw

Try block

PHP uses a keyword try to preface a block of code that is likely to cause an error condition.

Syntax


try
{
Code here;
}

If any exception occur in try block an exception handler associated with it handlers that exception. To associate an exception with try block you must put catch block after try blog.

Catch Block

It is used to catch the exception you can write multiple catch block for single try block. Each catch block contains handler of try block. Catch block code is executed when exception occur in try block.

Syntax

try
{
Code here;
}
Catch(ExceptionType name)
{
Code here;
}

Note:

If the exception occurs, PHP code after the statement will not be executed so that used try-catch block.

Throw

Throw statement is used to throw the new exception that require the single argument.

Syntax

throw new Exception;
you can also pass the custom  error message to the exception object

throw new Exception( “problem occur” );

Example with exception

function Fun($number) 
{
return $number;
}
  
try {
   $a = Fun(200);
  if($a > 80);
  throw new Exception("Value must be less than 80");
  
  
    if($a < 100);
  throw new Exception("Value must be greator than 100");
  
  
}


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

Output

Message: Value must be less than 80

Multiple exception

<?php

function Fun($number) 
{
return $number;
}
  
try {
   $a = Fun(200);
  if($a > 80);
  throw new Exception("Value must be less than 80");
  
  
    if($a < 100);
  throw new Exception("Value must be greater than 100");
  
  
}


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

?>

Output

Message: Value must be less than 80

If you want to learn more about error please visit
php tutorial



The following two tabs change content below.
Umar Farooque Khan is Software developer/ web developer and professional blogger serving Worldwide on freelancer and ODesk platform to show the capability of his skills He is the founder of pTutorial.com. The main purpose of this site is sharing and exchanging of I.T. Knowledge.

Latest posts by Umar Farooque Khan (see all)