Exception handling in PHP: Part 1


Concept of Exception

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. 

Different error handling methods

  • Basic use of exceptions
  • Creating a custom exception handler
  • Multiple exceptions
  • Re-throwing an exception
  • Setting a top level exception handler

Basic use of Exceptions

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.

Lets us see the concept with the example:

<html>
<
body bgcolor="pink">
<center>
<
h3> Basic use of Exceptions <h3>
<
hr>
<?php
//create function with an exception
function checkNum($number)
  {
 
if($number>1)
    {
   
throw new Except

ion("Value must be 1 or below");
    }
 
return true;
  }
 
//trigger exception
checkNum(2);
?>
</center>
</
body>
</html>

Save it as basic.php

Output of above

To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/basic.php 


basic exception.gif

The above output shows, the code get an exception which is uncaught exception.

Try, throw and catch in PHP

Here in this section we will understand the concept to avoid the error from the above scripting , we need to create the proper code to handle an exception.

  • Try - A function using an exception should be in a "try" block.
  • 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.

Let us see the above concept with the try, throw and catch :

<html>
<
body bgcolor="pink">
<center>
<
h3> Basic use of Exceptions with Try, Throw and catch  <h3>
<
hr>
<?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();
  }
?>
</center>
</
body>
</html>

Save it as basic.php

Output of above scripting

To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/basic.php 

basic exception1.gif

Further Error handling methods you will learn in my coming articles.

Thanks !!


Similar Articles