Error handling
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.
set_error_handler("customError");
Set Error Handler(contd.)
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//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.
<?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.