Practical-16
Write a PHP program for Error Handling.
Introduction
Error handling is an essential concept in building efficient and secure web applications using PHP. It is a fundamental part of programming as it makes sure that any issues that could arise or potential bugs in the code are corrected and handled in a smooth and timely manner. This guide explains the basics of error handling and the different techniques that can be used in PHP to effectively handle any type of errors. It also includes best practices and tools that can be used while writing efficient and secure PHP code.
In order to get a better understanding of error handling, it is important to know the different types of errors and exceptions that can occur in PHP. The most common type is the syntax error, which occurs when the code does not adhere to the correct syntax of the language. Other errors can include logic errors, which occur when a programmer does not correctly use the correct logic for the code. There are also runtime errors, which occur when a program is running and an exception is not handled properly. Finally, there are also user-defined errors, which occur when a custom error message is generated within the code.
The basics of error handling mainly revolve around catching exceptions and reacting to them in an appropriate manner. There are numerous ways to catch exceptions in PHP such as using the built-in error handler, using try-catch blocks, using custom callbacks, or using OOP syntax like exception classes. The recommended approach is to use a custom error handler to catch any exceptions and handle them accordingly.
Code
//Error handler function
function ErrorHandler($errno, $errstr, $errfile, $errline) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting, so let it fall
// through to the standard PHP error handler
return false;
}
switch($errno){
case E_USER_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "Aborting...<br />\n";
exit(1);
break;
case E_USER_WARNING:
echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
break;
case E_USER_NOTICE:
echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
break;
default:
echo "Unknown error type: [$errno] $errstr<br />\n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
//Set error handler
set_error_handler("ErrorHandler");
Output
My NOTICE [8] Uninitialized string offset: 0
The above code is an Error Handling Function which takes four parameters and returns true or false depending on the error type. The function defines various error types such as user errors, warnings, and notices and takes the appropriate action. It also sets the custom error handler using the set_error_handler() function.