Exception Handling in PHP

Advertisements

How to Install PHP PHP Fist Code

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

How to Install PHP PHP Fist Code

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements