How to handle errors in PHP

preview_player
Показать описание
When there is a lacks in PHP code then error throws out. A PHP error displays file name, line number, and message describing error.

These errors can be handled using one of the three ways.
1. Simple die() statement.
2. Creating custom error handler.
3. Trigger an error.

Let's explain each of these with examples.
1. Simple die() statement.
{
echo "file exists";
}
else
{
die("file does not exists");
}

2. Creating custom error handler.
We can create a special function customError(). We can throw this function using PHP's set_error_handler() if required. We are using two mandatory parameters error number and error message. There are three optional parameters are also available such as file name, line number, and error context.
function customError($err_no, $err_str)
{
echo "Error: [$err_no]: [$err_str]";
}
set_error_handler("customError");
echo($test);

3. Trigger an error.
We can trigger an error message when illegal input occurs. This is done using PHP's built-in trigger_error() function.
$no = 2;
if (no lt; 2)
{
trigger_error("Value must be at least 2 or more");
}
Рекомендации по теме
welcome to shbcf.ru