Error Handling in PHP
An error is an unexpected program result that cannot be handled by a program of its own. Error handling is the process of catching errors raised by the program and then taking appropriate action. Error handling is a powerful mechanism of PHP, which is used to handle runtime errors called Exceptions
What is an Exception?- An exception is an unexpected outcome of a program which can be handled by the program (whereas an error cannot be handled by a program of its own) where exceptions can be thrown and caught in PHP.
- When an error occurs, depending on the configuration settings, PHP displays the error message in the web browser with information relating to the error.
- PHP has a number of ways to handle errors.
Three Methods of Error Handling
- die statement
- Custom error handlers
- PHP error reporting
die Function
The die() function displays a message and exits the current script. It is an alias of the exit() function and it combines ‘echo’ and ‘exit’ function into a single one. The die() function returns no value.
Syntax:
die(message);
Eg:
<?php
$file_hand = fopen("rem.txt","r");
?>
The above code will generate a warning if rem.txt is not found in the specified directory (folder).
To avoid such warnings without creating negative impressions on the user, we have to carefully handle such warnings and errors . The above warning can be managed professionally using the die() function.
It is given below.
<?php
if(!file_exists("rem.txt"))
{
die("file not found");
}
else
{
$file=fopen("rem.txt","r");
}
?>
If the file does not exist then output will be:
file not found
Custom Error Handlers
PHP provides provision for the user to write user defined functions to handle any error. This function must be able to handle a minimum of two parameters. We will create a function that will be called when an error occurs in PHP.
Syntax:error_function($error_number, $error_message, $error_file, $error_line);
$error_number: It will be passed the level of the error raised as an integer. There are predefined error levels.
- 1 : .E_ERROR :fatal runtime error execution of script has been halted
- 2 : E_WARNING :non fatal runtime error execution of script has been halted
- 4 : E_PARSE :compile time error it is generated by the parser
- 8 :E_NOTICE :The script found something that might be an error
- 16 :E_CORE_ERROR :Fatal errors that occurred during initial startup of script
- 32 :E_CORE_WARNING :Non fatal errors that occurred during initial startup of script
- 2048: E_STRICT: Enabling PHP suggests changes to your code which will ensure forward compatibility of your code.
- 8191 :E_ALL :All errors and warning
- 8192: E_DEPRECATED : For receiving warnings about code that will not work in future versions.
$error_message: It will be passed the error message as a string.
$error_file: It is an optional parameter. It specifies the filename that the error was raised.
$error_line: It is also an optional parameter. It specifies the line number in which the error has occurred.
Note: There is a fifth parameter (optional), error_context, specifies an array containing every variable and their values in use when the error occurred. This parameter has been deprecated in PHP 7.2.0, and removed in PHP 8.0.0. So, it is better to avoid this parameter.
set_error_handler() Function
We need to set the user defined error handling function to tell 'PHP error handling' that the custom function will take care of the error, if any. The set_error_handler() function is used to set a user defined error handling function.
Check how PHP handles 'division by zero' error.
<?php
$x = 1; $y = 0;
$result = $x / $y; // division by zero to generate error
echo $result;
?>
Above code will generate the following warning with the default php error handling setup.
Let us define a custom function for handling the error - 'division by zero'
<?php
function test_error_handling($error_number, $error_message, $error_file, $error_line)
{
echo "<h4>Error Details</h4>";
echo "Error Number: ".$error_number;
echo "<br>Error Message: ".$error_message;
echo "<br>Error occurred in: ".$error_file;
echo "<br>Error occurred in the line: ".$error_line;
echo "<h4> Ending the execution... </h4>";
die(); // stopping the execution
}
// Setting set_error_handler
set_error_handler("test_error_handling");
$x = 1; $y = 0;
$result = $x / $y; // division by zero to generate error
echo $result;
?>
Output:
Error Details
Error Number: 2
Error Message: Division by zero
Error occurred in: C:\wamp64\www\index.php
Error occurred in the line: 319
Ending the execution...
PHP Exception Handling
Exception handling is somewhat similar to the conditional statements. They change the flow of the php script if a predefined error condition occurs. When the specified error occurs, a user defined exception handler function is called by the program. Further execution of the code depends on the user defined error handler function. User defined error handler function may execute some other code from some other location to overcome the exception.
Exception Handling using 'try…catch' Method
The primary method of handling exceptions in PHP is the try…catch. When a PHP exception is 'thrown', the PHP runtime looks for a catch statement which can take care of that type of exception.
Syntax:
try {
// code execution
}
catch (exception $e) {
//code to handle the exception
}
finally {
//this code runs always
}
- try: The try block contains the code that may "throw" an exception. If the exception is triggered, an exception will be 'thrown". If the exception does not trigger, the code will execute as normal.
- throw: The "throw" keyword triggers a PHP exception which should be handled. The PHP runtime will try to find a "catch" statement to handle the exception.
- catch: When an exception is thrown, PHP runtime will check for a corresponding "catch" block. The code inside the "catch" block is specified in such a way that it will handle the exception thrown from the "try" block.
- finally: The "finally" keyword is used to run a block of code irrespective of whether an exception has occurred or not.
Note: PHP allows multiple "catch" blocks to serve different types of exceptions "thrown" from the "try" block.
Method | Syntax | Description |
---|---|---|
getCode() | $e->getCode(); | It returns an integer which is used to identify the exception. |
getFile() | $e->getFile(); | It returns the path to the file where an exception occurred. |
getMessage() | $e->getMessage(); | It returns a message about the error. |
getLine() | $e->getLine(); | It returns the number of the line of the code where an exception occurred. |
getTrace() | $e->getTrace(); | It returns an 'n' array of the backtrace() |
getTraceAsString() | $e->getTraceAsString(); | It returns a trace as a string. |
<?php
function divisionResult($number1, $number2)
{
if($number2 == 0)
{
throw new Exception("Division by zero is undefined!");
}
else
{
return number_format($number1/$number2, 2, '.', '');
}
}
try
{
$result = divisionResult(10,0);
echo $result ;
}
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
finally
{
echo "<h4>Code execution completed.<h4>";
}
?>