PHP Try, Throw and Catch

Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008

0

Exceptions can occur in your program and you need to handle them to have your code going on. But how would you know which code is going to produce an error.

PHP exception handling provides some easy steps to deal with the exceptions:

  • track where an error is produced
  • throw the error to some handler
  • catch the appropriate error and continue with the execution

A proper exception code includes:

  • Try – It encloses the block of code or the function which is doubted to produce an exception. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is thrown automatically.
  • Throw – Throw lets you trigger an error manually.
  • Catch – It contains the code to handle the exceptions. A “catch” block retrieves an exception and creates an object containing the exception information.
    A simple try-catch example:

    <?php
    //create function with an exception
    function checkNum($number)
    {
    if($number<1)
    {
    throw new Exception(”Number must be greater than 0″);
    }
    return true;
    }
    //trigger exception in a “try” block
    try
    {
    checkNum(2);
    //If the exception is thrown, this text will not be shown
    echo ‘The number is greater than 0′;
    }
    //catch exception
    catch(Exception $e)
    {
    echo ‘Message: ‘ .$e->getMessage();
    }
    ?>

    Error Output:

    Message: Number must be greater than 0

The code above throws an exception and catches it.It works as follows:

  • The checkNum() function is created. It checks if a number is less than 1. If it is, an exception is thrown
  • The checkNum() function is called in a “try” block
  • The exception within the checkNum() function is thrown
  • The “catch” block retrives the exception and creates an object ($e) containing the exception information
  • The error message from the exception is echoed by calling $e->getMessage() from the exception object

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.