Exception Handling in PHP


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

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain, Tutorialday.com, SeosmoTools.com @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: hitesh.xc@gmail.com WhatsApp no. 8882538826

Yahoo Advertisements