Broad Network


Basics of Exceptions in PHP

Exception Handling in PHP - Part 1

Forward: In this part of the series we look at the basics of exceptions in PHP.

By: Chrysanthus Date Published: 11 Aug 2012

Introduction

This is part 1 of my series, Exception Handling in PHP. In this part of the series we look at the basics of exceptions in PHP. You need basic knowledge in PHP and PHP Object Oriented Programming in order to understand this series. If you do not have knowledge in any of those fields then from this blog, read the series whose first part is titled, “Getting started with PHP” and another whose first part is titled “OOP Basics in PHP”. To reach any of the series, just type the title and my name Chrys in the Search Box of this page and click Search.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Runtime Error Example
Consider the following code:

<?php

    $numerator = 8;
    $denominator = 2;

    if ($denominator != 0 )
        {
            $answer = $numerator/$denominator;
            echo $answer;
        }
    else
        {
            echo "Division by zero is not allowed!";
        }

?>

This code basically divides two numbers. In life you cannot divide a number by zero. Assuming that the denominator is input by the user, he may input zero. The division (process) by zero should not be allowed.

Let us look at what is in the code: the first two statements are initialization of integers. The division should take place in the if-block. The if-condition checks whether the denominator is zero. If it is not, the division takes place in the if-block. If it is, the else part of the if-construct displays an error message to the user. This code segment is OK, because if the denominator is zero, the if-block will not be executed and no division will take place. With the above code, the execution of the program continues after the if/else construct.

This if/else construct does the division and prevents runtime error from taking place. The if-block does the division; the if-condition checks if error would occur; if error would occur, the else block displays an alert message and the if-block and division are not executed.

Basic Components of Exception
In simple terms, exception is an error. With exception handling, you have what is called the try/catch construct; made up of the try and catch blocks. The try block has an important expression, which is, throw. throw takes a new object called the Exception Object. The Exception object is a predefined object that helps you handle exceptions.

In the above if/else construct, the code segment of interest, which is the segment required, is the if-block. This if-block is what does the division. With Exception handling, that code segment of interest goes into the try-block; the error message code segment or error handler code segment goes into the catch-block. The throw expression in the try-block calls the catch-block passing a new exception object to it. The catch construct is like a function. This is the basic syntax for exception handling,

    try
        {
            //statements of interest
            throw new Exception(errorMessage, code);
        }
    catch (Exception $e)
        {
            //handle the error
        }

The argument for the throw expression does not go into parentheses. It is a new Exception instantiated object that does not need to have a name. You can twist your code around to give it a name, but it is all right as it is above. The parameters of the new exception object are both optional. The first one is the error message of your choice you want to give to the user of the program. The second one is an integer of your choice that represents the error.

The catch-block should immediately follow the try-block in your typing, as in the above syntax. It receives the new instantiated exception object thrown. The parameter for the catch block is, “Exception $e”. Here, the word, Exception, means the type of object received, is an exception object. $e is the variable that identifies the new instantiated exception object (received in the catch-block).

The previous program is re-written using the try/catch construct as follows:

<?php

    $numerator = 8;
    $denominator = 2;

        try
            {
                if ($denominator != 0 )
                    {
                        $answer = $numerator/$denominator;
                        echo $answer;
                    }
                else
                    {
                        throw new Exception("Division by zero is not allowed!");
                    }
            }
        catch (Exception $e)
            {
                echo $e->getMessage();
            }

?>

Read and try the above program. Change the value of $denominator to zero and try the program again. Remember, for the throw operand above, the two arguments of the constructor function of the Exception class are optional. In this code, only the error message of the programmer’s choice has been given. If the programmer does not give this argument, the default error message of “Unknown exception” would be held by the new instantiated exception object.

The catch-block catches the exception object thrown as the parameter (argument), $e. The Exception class has a method that would read the error message you typed during the instantiation of the new exception object. The name of the method is, getMessage. The catch-block above simply echoes the message.

Read through the above code again. In many cases, the try-block equivalently has an if-condition whose block will execute if the condition does not detect the error. If the condition detects the error, the if-block will not execute, and the else part will throw the exception; that is, the else part will call the catch-block sending the argument (instantiated exception object) of the throw expression, to it. The catch block uses the argument to display an appropriate error message (typed in during instantiation) to the user. This is what happens in many cases. Errors are not usually handled in the real sense of the word; usually an error message is sent to the user, an if-construct in the try block prevents the error from actually occurring. After this execution, the program continues in sequence from the try/catch construct; and there is no termination of program even if an error was detected.

Throw Expression in a Function
You can put what you need for the try block in a function as illustrated below:

<?php

    $numerator = 8;
    $denominator = 2;

    function errFn()
        {
            if ($denominator != 0 )
                {
                    $answer = $numerator/$denominator;
                    echo $answer;
                }
            else
                {
                    throw new Exception("Division by zero is not allowed!");
                }
        }

        try
            {
                errFn();
            }
        catch (Exception $e)
            {
                echo $e->getMessage();
            }

?>

Here, the try-block only calls the function. The function has the if/else construct and the else part of the construct throws the exception (object).

We have learned that the throw expression can be in the try block directly or in a function called by the try block. However, the catch block remains attached to the try block.

Note: In practical programming, most catch blocks just send an error message to the user of the program; they do not really correct the error.

Note: in the try block, any statement after the throw statement is not executed.

Let us take a break here and continue in the next part of the series.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message