articles

Home / DeveloperSection / Articles / PHP Exception

PHP Exception

Anonymous User6642 15-Sep-2011

PHP 5 has an exception model similar to that of other programming languages. Exceptions are used to change the normal flow of a script if a specified error occurs. An exception can be thrown, and caught (catch) within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.

Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.

There is mainly three factors which is used for handling exception in PHP.
  1.    Try block: Try block is a block where suspected line of code is kept, that is try block contains that code block where exception might be generate.
  2.    Catch block: Catch block is a block of code where we handle the generated exception.
  3.   Throw: Throw is a keyword which is used for throwing your own exception. 
Let’s we have an example, how to handle exception within the PHP script.
Example:
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <title>PHP Exception</title>
    </head>
    <body>
        <?php
           
            function MyException($num1, $num2)
            {
                // Division by Zero exception genrate
                return $num1/$num2;               
            }
           
            try
            {
                // call MyException function which raised division by zero function
                MyException(12,0);
            }
            catch (Exception $e)
            {
                // Handle exception, print exception message
                echo $e;
            }
        ?>
    </body>
</html>

 

When you run above file the following exception will be generated.

Warning: Division by zero in C:\Apache Server\htdocs\MySiteFile\PHPException.php on line 16

Throw Exception:

‘throw’ keyword is used for throw exception in PHP script, with the help of  throw keyword we can throw exception to another catch block where exception is handling. ‘throw’ keyword has at least one catch block of statement for handling exception.

Let’s we have an simple example, how to throw exception in PHP.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <title>PHP Exception</title>
    </head>
    <body>
        <?php
           
            function MyException($num1)
            {
                   if($num1 > 4)
                   {
                       // throw the exception
                      throw new Exception("<b>Number should be less than 4</b>");
                   }
                   echo 'Given number is less than 4'; 
            }
           
           
            try
            {
                // call MyException function which raised exception
                MyException(12);
               
                echo '<b>this is executed when number is less than 4</b>';
            }
            catch (Exception $e)
            {
                // Handle exception, print exception message
                echo '<b>Exception is :</b>'.$e;
            }
            ?>
    </body>
</html>

 Output:

Exception is : exception 'Exception' with message 'Number should be less than 4' in C:\Apache Server\htdocs\MySiteFile\PHPException.php:19 Stack trace: #0 C:\Apache Server\htdocs\MySiteFile\PHPException.php(28): MyException(12) #1 {main}

Creating Custom Exception Class:

Creating custom exception handler is quite easy. We simply create a class ‘CustomException’, inherit the Exception class and create an exception handler function that can be called when PHP exception occurs.

Here I am giving an example to handling PHP exception with the help of custom exception class.

Example:
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <title>PHP Exception</title>
    </head>
    <body>
        <?php
       
            class CustomException extends Exception
            {
                public function ErrorMessage()
                {
                    $errmsg ='<b>Error Line :</b> '.  $this->getLine().'</br><b>Error File : </b>'. $this->getFile().'</br><b>Error Message : </b>'. $this->getMessage();
                    return $errmsg;
                }
            }
                $email = "arunbaswar@gm....ail.com";
            // check email is valid or not
                // starting try block
                try
                {
                    if(filter_var($email, FILTER_VALIDATE_EMAIL)==false)
                    {
                        // throw the exception
                        throw new CustomException($email);
                    }
                    else
                    {
                        echo 'email id is valid';
                    }
                }
               catch (CustomException $ae)
               {
                   echo $ae->ErrorMessage();
               }
    
            ?>
    </body>
</html>
Output:

PHP Exception

Re-Throwing Exception:

Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way.

Let’s we have an example, how to re-throw an exception in PHP.

Example:
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <title>PHP Exception</title>
    </head>
    <body>
        <?php
       
            class CustomException extends Exception
            {
                public function ErrorMessage()
                {
                    $errmsg ='<b>Error Line :</b> '.  $this->getLine().'</br><b>Error File : </b>'. $this->getFile().'</br><b>Error Message : </b>'. $this->getMessage();
                    return $errmsg;
                }
            }
                $email = "arunbaswar@gm....ail.com";
            // check email is valid or not
                // starting try block
                try
                {
                    try
                    {
                        if(filter_var($email, FILTER_VALIDATE_EMAIL)==false)
                        {
                            // throw the exception
                            throw new CustomException($email);
                        }
                        else
                        {
                            echo 'email id is valid';
                        }
                    }
                   catch (CustomException $ae)
                   {
                       // re- throw the php exception
                       throw new CustomException($email) ;
                   }
                }
                catch(CustomException $e)
                {
                    // display custom class message
                      echo $e->ErrorMessage();              
                }
            ?>
    </body>
</html>

 

Output:

PHP Exception



Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By