Exception Handling in PHP

Google Advertisements

Prev Tutorial Next Tutorial

Exception Handling in PHP

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.

Without Exception Handling

PHP Code Without Exception Handling

<?php
//create function with an exception
function checkNum($number)
{
  if($number>1) 
  {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

//trigger exception
checkNum(2);
?>

Output

Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

To avoid above error or problem you shoud be use Exception Handling concept in PHP. To avoid the error from the example above, we need to create the proper code to handle an exception.

Try, throw and catch

Try: A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".

Throw : This is how you trigger an exception. Each "throw" must have at least one "catch".

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

PHP Syntax

<?php
//create function with an exception
function checkNum($number) 
{
  if($number>1) 
  {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

//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
catch(Exception $e) 
{
  echo 'Message: ' .$e->getMessage();
}
?>

The code above will get an error like below.

Output

	
Message: Value must be 1 or below

Prev Tutorial Next Tutorial

Download Projects

Adsense Advertisements
Free Classified Site – Bedpage

Yahoo Ads Advertisements