Data Science and Machine Learning Internship ...
- 22k Enrolled Learners
- Weekend/Weekday
- Live Class
Error handling is the process of finding errors raised by your program and taking action. This article will help you explore the concept of PHP Error Handling In detail. Following pointers will be covered in this article,
Let us get started with PHP Error Handling article,
It is very easy in PHP to handle errors. When creating scripts and web applications, error handling is a very important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
We will see different error handling methods:
*Simple “die()” statements
*Custom errors and error triggers
*Error reporting
Let us see how PHP Error Handling works with die function,
Using die ( ) function
When writing your PHP program you should check all possible errors before going ahead and take the appropriate action required. Example without having /tmp/test.xt file
<?php If(!file_exists (“/tmp/test.text”)) { die(“File does not founds”); } else { $file = fopen(“/tmt/test.txt”,”r”); Print"opening file successfully”; } } ?>
Creating a Custom Error Handler
Creating a custom error handler is very simple. We can simply create a special function that can be called whenever an error occurs in PHP code.
This function is able to handle a minimum of two parameters that may be error level or error message but can accept upto five optional parameters, they are file, line-number, and the error context
Syntax
error_function() Set Error Handler
The default error handler for PHP is the built-in error handler given in the software. We are going to make the function above the default error handler for the duration of the script.
It is possible to change the error handler which is applied for only some errors, in that way the script can handle different errors in different ways in the code. However, in this example, we are going to use our custom error handler for all the errors in it.
set_error_handler(“’’);
Let us take a look at a sample program,
Testing the error handler by trying to output a variable that does not exist:
<?php //error handler function function custom error($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } set_error_handler("customError"); echo($test); ?>
Output
Error: [8] Undefined variable: test
This brings us to the end of this article.
If you found this blog relevant, check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.
Got a question for us? Please mention it in the comments section of article and I will get back to you.
edureka.co