The Wayback Machine - https://web.archive.org/web/20240706041937/https://www.geeksforgeeks.org/error-handling-in-php/
Open In App

Error handling in PHP

Last Updated : 21 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:  

  • Using die() method
  • Custom Error Handling

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

die( $message )

Example:  

php




<?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
 
// 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: It is required parameter and it must be an integer. There are predefined error levels.
  • $error_message: It is required parameter and it is the message which user want to print.
  • $error_file: It is optional parameter and used to specify the file in which error has been occurred.
  • $error_line: It is optional parameter and used to specify the line number in which error has been occurred.
  • $error_context: It is optional parameter and used to specify an array containing every variable and their value when error has been occurred.

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

  • 1 : .E_ERROR :fatal runtime error execution of script has been halted
  • 2 : E_WARNING :non fatal runtime error execution of script has been halted
  • 4 : E_PARSE :compile time error it is generated by the parser
  • 8 :E_NOTICE :The script found something that might be an error
  • 16 :E_CORE_ERROR :Fatal errors that occurred during initial startup of script
  • 32 :E_CORE_WARNING :Non fatal errors that occurred during initial startup of script
  • 8191 :E_ALL :All errors and warning

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




<?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.



Previous Article
Next Article

Similar Reads

Error Handling with Error Boundary Hooks
In the world of web development handling errors effectively is crucial for providing a seamless user experience. React one of the most popular JavaScript libraries provides a powerful feature known as Error Boundary Hooks that allows developers to handle errors in their applications. In this article, we will explore how Error Boundary Hooks can be
2 min read
How to retrieve error message using Exception class in PHP when error occurred ?
Exception handling is the important part of PHP in which we deal with how to maintain the flow of the program if there is an error or exception that occurs during the compilation. As you know we can handle the exception by throw, try-catch, die method so now we understand how to retrieve the error message using exception class by given below exampl
2 min read
Handling 404 Error in Flask
Prerequisite: Creating simple application in Flask A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page. GeeksforGeeks also has a customized error page. If we t
4 min read
Javascript Error and Exceptional Handling With Examples
An error is an action that is inaccurate or incorrect. There are three types of errors in programming which are discussed below: Syntax errorLogical errorRuntime error Syntax error: According to computer science, a syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming
3 min read
Different error handling in "Promise.resolve" vs "new Promise" constructor
In JavaScript, there are two ways to create a promise: using the Promise.resolve method or using the new Promise constructor. While both ways achieve the same result, they handle errors differently. Promise.resolve: The Promise.resolve method takes in a value and returns a promise that is resolved with that value. If the value is a promise, the ret
3 min read
The 'new' operator in Javascript for Error Handling
In this article, we will see new operator usage during error throwing as well as handling the error() method in JavaScript using theoretical as well as coding examples. JavaScript new operator: The new operator is actually a special operator that is used along with the error() method which is the method for the error class used to instantiate any s
3 min read
JavaScript Error Handling: Unexpected Token
Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + - var if-else var etc}. Unexpected token is similar to syntax error but more specific.Semicolon(;) in JavaScript plays a vital role while wr
3 min read
Error Handling in Express
Error handling in Express is referred to as something that handles or processes errors that may come while executing any synchronous code or asynchronous code. What do we mean by synchronous or asynchronous code? A lot of times, it happens that an operation begins executing but for some reason faces some delay before completion. The common examples
6 min read
Error Handling in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. In any application, Error, and Exception handling
8 min read
Explain some Error Handling approaches in Node.js
Node.js is an open-source JavaScript runtime environment. It is often used on the server-side to build API for web and mobile applications. A large number of companies such as Netflix, Paypal, Uber, etc use Node.js. Prerequisites: PromisesAsync Await An error is any problem given out by the program due to a number of factors such as logic, syntax,
3 min read
three90RightbarBannerImg