Exception Handling in PHP

Google 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 Advertisements

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

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

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

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user. Cloud Computing Tutorial

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects. Download Java C C++ Projects

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: hitesh.xc@gmail.com or 8076671483 Try this Keyword C++ Programs