ERROR HANDLING
die() function
• The die() is an inbuilt function in PHP.
• It is used to print message and exit from the current php
script. It is equivalent to exit() function in PHP.
die() function(contd.)
<?php
if(file_exists("mytestfile.txt")) {
$file = fopen("mytestfile.txt", "r");
} else {
die("Error: The file does not exist.");
}
?>
OUTPUT:
Error: The file does not exist.
Custom Error Handler(contd.)
Parameter Description
error_level Required. Specifies the error report level for the user-defined
error. Must be a value number.
error_messag Required. Specifies the error message for the user-defined
e error
error_file Optional. Specifies the filename in which the error occurred
error_line Optional. Specifies the line number in which the error occurred
error_context Optional. Specifies an array containing every variable, and their
values, in use when the error occurred
error_level: These are the possible error level which are
listed below:
• 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
• 8191 :E_ALL :All errors and warning
Set Error Handler
• The default error handler for PHP is the built in error
handler.
set_error_handler("customError");
Set Error Handler(contd.)
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
OUTPUT:
Error: [8] Undefined variable: test
Trigger an Error
• In a script where users can input data it is useful to trigger errors
when an illegal input occurs.
• This is done by the trigger_error() function.
<?php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below");
}
?>
OUTPUT:
Notice: Value must be 1 or below in C:\xampp\htdocs\trigger.php on
line 4
Trigger an Error(contd.)
• An error can be triggered anywhere you wish in a script, and by
adding a second parameter, you can specify what error level is
triggered.
• Possible error types:
• E_USER_ERROR - Fatal user-generated run-time error. Errors
that can not be recovered from. Execution of the script is halted
• E_USER_WARNING - Non-fatal user-generated run-time
warning. Execution of the script is not halted
• E_USER_NOTICE - Default. User-generated run-time notice.
The script found something that might be an error, but could
also happen when running a script normally