PHP Exception Handling



PHP Exception Handling : try, throw and catch

The exception is one of powerful mechanism to handle the run-time errors.

An exception is a situation that occurs during the execution of a program.
When exception occurs the normal flow of code is changed if a error condition occurs. This condition is called an exception.

The exception occur in when below situation occurs.

  • User try to open file that can not be found.
  • User enter invalid data.

The Exception are more useful over error handling. We can handle exception using Try, Throw and Catch in PHP.


PHP  Try Block

The try bock contain a block of program code which exception may occur.
A try block always followed by a catch block which handle the exception. If exception not occur then code of program smoothly continue.
Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.

Syntax of try block

try
{
//block of program statement
}


PHP Catch Block

The catch block must be with a try block. If the exception occurs in try block then the catch block executes. Exceptions can be thrown within a catch block.

Syntax of catch block

try
{
//block of program statement
}
catch ()
{
//error handling code
}


PHP Throw Block

Each throw must have at least one catch block. A Throw how you trigger an exception.

Example of Exception Handling in PHP

<?php
//create function to check no. is odd or even
function inputnumber($num) {
if($num%2 != 0) 
{
throw new Exception("Error !! The number is odd");
}
return true;
}

try 
{
inputnumber(2);
echo 'The number is even';
}
catch(Exception $e) 
{
echo $e->getMessage();
}
?>

Above php example we check the number is odd or even, here we input “2” so the result is “The number is even”.

 PHP form Example of Exception Handling

Here, we took same above example with php form like below:

<form method="post">
Enter Number :
<input type="text" name="name"><br/>
<input type="submit" value="Check" name="Submit1"> <br/>
 
</form>

<?php
if(isset($_POST['Submit1']))
{ 
//create function to check no. is odd or even
function inputnumber($num) {
  if($num%2 != 0) 
  {
    throw new Exception("Error !! The number is odd");
  }
  return true;
}

try 
{
  inputnumber($_POST["name"]);
  echo 'The number is even';
}
catch(Exception $e) 
{
  echo $e->getMessage();
}
}
?>

</body>
</html>

The PHP example out put is :

PHP_exception
PHP Exception : Try, catch block Example

 

Leave a Reply

Your email address will not be published. Required fields are marked *