Exception Handling in PHP
Foreword: In this tutorial, I talk about error handling by what is known as exception. You should have read the previous parts of the series, before reaching here, as this is the continuation.
By: Chrysanthus Date Published: 17 Nov 2018
Introduction
Runtime Errors
Runtime errors occur when the program is being executed as a result of the fact that you did not take certain factor into consideration when coding. For example, let us say your code is to divide 8 by some denominator that the user inputs. If the user inputs 2, the division will work, giving you 4 as answer. If the user inputs zero, the division will not work, because 8/0 has no answer. When a runtime error occurs your program normally crashes (and stops). To solve runtime error, you have to write code that will prevent the execution of the particular code segment from taking place. In this division example, you have to write code that will prevent division by zero from taking place, and possibly informing the user of the mistake he made by inputting zero as a denominator.
Preventing Runtime Errors
Runtime errors can be prevented using what is called a try-catch construct. I will use the example of dividing 8 by a denominator to illustrate this. Consider the following code:
<?php
$input = 2;
try
{
if ($input == 0)
throw new Exception("Division by zero is not allowed!");
$answer = 8 / $input;
echo $answer;
}
catch (Exception $err)
{
echo $err->getMessage();
}
?>
Test the whole code. You should have 4 as the answer, displayed. Now change the value of the variable, $input at the beginning of the code from 2 to 0. You should have the text, “Division by zero is not allowed!” displayed.
The code divides 8 by the value of $input. When the value of the input variable is not zero, everything is fine. When the value is zero, that is an error, and so the program should not crash. Code has to be written to prevent the program from crashing.
There are three things you should note about the code above. There is the try-block; there is the catch-block and there is a throw statement, which throws the exception. This throw statement actually creates an object from a PHP pre-defined (internal) class, called Exception. The string is the error message to be displayed, to the user.
The try-block begins with the reserved word, try, then you have the pair of curly brackets. The statements meant for the try block are in the curly brackets. The statements for the overall code that do division by zero, should be placed inside the try block.
The catch-block begins with the reserved word, catch. It has parentheses with a parameter. The parameter begins with the exception class name (type) ; this is followed by the exception object, a name of your choice. The catch-block has a pair of curly brackets. The statements meant for the catch block go into the curly brackets.
The very first statement in the try-block is an if-statement combined with what is called the throw statement? The idea is that you check if the input value is zero. If it is zero, then the throw statement is executed to prevent crash. When the throw statement is executed, we say an exception is thrown. When an exception is thrown, the statements below the throw statement in the try block are not executed; while the statements in the catch-block must be executed. That is, when an error occurs, the statements below the throw statement in the try-block are not executed, while the catch-block must be executed to handle the problem. If no error occurs (in this case, input is not zero), then an exception will not be thrown. If an exception is not thrown, the statements below the throw statement in the try-block are executed, and the catch-block is not executed.
The try-block has the normal statements to be executed to solve task required by the program. These statements are executed on condition that no error occurred. The catch block has the statements to be executed if an error occurs. Usually what the catch block does is that it simply informs the user that an error has occurred with a brief description of the error; the rest of the program below the try-catch blocks continues to run. If the error is detected in the try block and the catch block is executed as in the above code, then the program will not crash. Prevention of crash is as a result of the fact that the normal statements in the try block are not executed and the catch-block is executed. So, with the try-catch construct, and error or no error, the code above and below the try-catch construct are executed.
Remember, when there is no error, the throw statement is not executed; the catch block is also not executed; but the required statements in the try block are executed.
An instantiated exception object, is an object which indicates that something terrible will happen, if action is not taken.
PHP has an internal (predefined) class called, Exception. Whenever an exception is thrown, the object for this class, instantiated when the exception is thrown, acquires the filename and the directory name of the running file, the line number in the file where the error occurred, as well as the message you give. Try the following code, which shows these exception object properties in action, in the catch block:
<?php
$input = 0;
try
{
if ($input == 0)
throw new Exception("Division by zero is not allowed!");
$answer = 8 / $input;
echo $answer;
}
catch (Exception $err)
{
echo $err->getMessage(), '<br>';
echo $err->getFile(), '<br>';
echo $err->getLine(), '<br>';
}
?>
The catch block is like a function block. The parameter is the instantiated object of the Exception class. The output is something like:
Division by zero is not allowed!
C:Apache24htdocstemp.php
8
That is it for this part of the series.
Chrys
Related Links
Basics of PHP with Security ConsiderationsWhite Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links