PHP Error Handling | Two types of Error in PHP
×

Error Handling in PHP

3868

Error handling is the procedure of catching the errors raised by the program and then taking proper action. If you would handle the errors appropriately, then it may lead to several unexpected consequences.

There are two types of error in PHP:

  • Internal Error
  • External Error

In a code when a logic error exists, then it is called internal error. Using good programming practice, we resolve logic error.

An error doesn't present in a program or code, and then it is called external error.

For e.g. connection failed with network, database connection failed.

How to resolve PHP errors?

Using the die () function, we resolve the PHP errors. This method is very easy for error handling.

PHP code:

<?php

if(file_exists("txtfile1.txt"))
{
//if file exist then file is open
$my_file=fopen("txtfile1.txt","r");
}
else
{
die("Given filename doesn't exist in a folder");
}

?>
Result:


In PHP many predefined errors are present is known as built in error. every predefined errors have own value i.e. E_NOTICE predefined error value is 8, E_USER_WARNING value is 512, E_USER_NOTICE value is 1024, E_ALL value is 8191.

For example:

  • E_NOTICE
  • E_ERROR
  • E_WARNING
  • E_USER_ NOTICE
  • E_CORE_ERROR
  • E_CORE_WARNING
  • E_USER_ERROR
  • E_USER_WARNING
  • E_COMPILE_ERROR
  • E_COMPILE_WARNING
  • E_PARSE
  • E_ALL

To handle this types of errors we create own function. Function name is error_handling_function($error_number, $error_string) and we used a inbuilt handler function set_error_handler().

For Example:

<?php

// defined error handler function
function error_handling_function($error_number, $error_string)
{
echo "<td>Error:</td> [$error_number] $error_string";
}
// set error handler function are used
set_error_handler("error_handling_function");
echo($ErrorTrigger);

?>

Result:


Now we use E_USER_WARNING error  value is 512.

<?php

function error_handling_function($error_number, $error_string) {
echo "<b>Error No [$error_number]:</b> $error_string<br />";
echo "End of the program..";
die();
}
// set error handler
set_error_handler("error_handling_function", E_USER_WARNING);
// error test by user
$value=102;
if ($value>=101)
{
trigger_error ("value defined by user is 101 or less than 101", E_USER_WARNING);
}

?>

Result:




Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments