Open In App

Error handling in PHP

Prerequisite: Types of Error 
PHP is used for web development. Error handling in PHP is almost similar to error handling in all programming languages. The default error handling in PHP will give file name line number and error type.
 

Ways to handle PHP Errors:  



Basic error handling: Using die() function The die() function print a message and exit from current script.
Syntax:  

die( $message )

Example:  






<?php
 
// Php code showing default error handling
 
$file = fopen("geeks.txt", "w");
?>

Note: Run the above code and geeks.txt file is not present then it will display an run-time error message. 
Runtime Error: 

 PHP Warning: fopen(geeks.txt): failed to open stream: Permission denied 
in /home/dac923dff0a2558b37ba742613273073.php on line 2

To prevent this error use die() function. Below is the implementation of die() function:
Example:  




<?php
 
// PHP code to check errors
 
// If file is not present
// then exit from script
if( !file_exists("geeks.txt") ) {
    die("File is not present");
}
 
// If file is present
// then continue
else {
    $file = fopen("geeks.txt", "w");
}
?>

Note: If geeks.txt file not present then it will display output. 
Output 

File is not present

Custom Error handling: Creating a custom error handler in PHP is quite simple. Create a function that can be called when a error has been occurred in PHP.
Syntax:  

error_function( $error_level, $error_message, $error_file, $error_line, $error_context)

Parameters: This function accepts five parameters as mentioned above and described below:  

error_level: These are the possible error level which are listed below: 

set_error_handler() Function: After creating myerror() function need to set custom error handler because in normal way PHP handles it but if user doing custom error handling then user have to set it in place of argument and pass out myerror function as a string.
Example: 




<?php
 
// Creates my error function which prints message
//to user
function myerror($error_no, $error_msg) {
    echo "Error: [$error_no] $error_msg ";
    echo "\n Now Script will end";
     
    // When error occurred script has to be stopped
    die();
}
 
// Setting set_error_handler
set_error_handler("myerror");
 
$a = 10;
$b = 0;
 
// This will generate error
echo($a / $b);;
?>

Output: 

Error: [2] Division by zero 
 Now Script will end

Conclusion: It is always try to error handling using Custom error handling because it will show more specified message according to the user that can be helpful to the user. If error is not handle using Custom error handling then a error occurred then out script will be halted by default but if it handle error using Custom error handling then it can continue script after displaying error message.


Article Tags :