Error handling is a simple but essential part of web-based applications. It is considered a dynamic part of the programming language. Without proper error management, applications will appear unprofessional, full of bugs, and may open up unknown security threats. This tutorial explains the concept of error handling in PHP.

What Is Error Handling?

Error handling is a method of capturing an error thrown by a program and applying appropriate action to resolve that error. PHP displays an error message with the file name and line number by default.

There are two popular ways to handle errors in PHP:

  1. Applying die() method
  2. Custom errors handler and error triggers

Applying die() method

The die() method terminates the execution of the current PHP script and prints a message as output.


/* File opening in read mode */
$fp = fopen("example.csv", "r");

The above code is trying to open a file that does not exist. So it will give an error message such as:

( ! ) Warning: fopen(example.csv): failed to open stream: No such file or directory in D:\wamp64\www\test1.php on line 8

If the program requires this file, then without it, further script execution may become unusable, so here there is a need to stop the execution and display a custom error message using the die() function.


/* Check if the file exists */
if(!file_exists("example.csv")) {
  die("error: The required file is missing.");

/* File opening in read mode */
$fp = fopen("example.csv", "r");


error: The required file is missing.

Custom Errors Handler Function

In PHP, we can define our custom error handling function, which is straightforward to create. This function requires a minimum of two parameters and supports a maximum of five parameters.


custom_error_function(error_no, error_message, error_file, error_line, error_context)

Parameter Values

Parameter Description
error_no It is required and must be a value number. It sets the level of error reporting for a user-defined error.
error_message It is required and prints the user-defined error message.
error_file It is optional. It specifies the file where an error has occurred.
error_line It is optional. It prints the line where an error has occurred.
error_context It is optional. When an error occurs, it prints an array containing all the variables with values.

Set Error Handler

The PHP set_error_handler() function is a built-in error handler function that sets the error handler function defined by the user.


set_error_handler(errorhandler, E_ALL | E_STRICT)

Parameter Values

Parameter Description
errorhandler It sets a user error handling function name.
E_ALL|E_STRICT It specifies at which error report level the error defined by the user will be shown. The default value is E_ALL.
Constant Description
E_ERROR Run time fatal errors. Stop the execution of the script.
E_WARNING Run time non-fatal errors. Do not stop the script execution.
E_PARSE The parser generates the compile-time parsing error.
E_NOTICE The script found something that could be an error.
E_CORE_ERROR The fatal errors at the initial start-up of PHP
E_CORE_WARNING Run time non-fatal errors occurs at the initial start-up of PHP.
E_USER_ERROR User-generated fatal error.E_ERROR  generated by the programmer by using trigger_error()
E_USER_WARNING User-generated non-fatal warning.E_WARNING  generated by the programmer by using trigger_error()
E_USER_NOTICE User-generated run-time notice.E_NOTICE  generated by  the programmer by using trigger_error()
E_STRICT User-generated run-time notice
E_RECOVERABLE_ERROR Catch fatal errors. It is similar to E_ERROR but caught by the user-defined handle.
E_ALL It captures all the warnings and errors, except E_STRICT


/* User-defined error handling function */
function customErrorHandlar($errorNo, $errorMessage, $errorFile, $errorLine) {
  echo "Error Message: [$errorNo] $errorMessage<br>";
  echo "Error on line $errorLine in $errorFile";

/* Set Error Handler */

echo $hello;


Error Message: [8] Undefined variable: hello
Error on line 10 in D:\wamp64\www\example.php

Exception Handling

Like all other programming languages, PHP also has an exception handling model. There are three keywords related to exception handling in PHP. These are as follows:

Keyword Description
try In the "try" block, codes are written in which there may be an exception. If there is no exception, this code execution will continue. Otherwise, it "throws" an exception.
throw If an exception is triggered, the control is transferred from the try block to the catch block using the keyword "throw". Each "throw" must have a "catch".
catch The catch block catches the exception and creates an object which will hold exception information.


  if(!file_exists("example.csv")) {/* Check if the file exists */
    throw new Exception("error: The required file is missing.");
  $fp = fopen("example.csv", "r"); /* Open the file. */
catch (Exception $err) {
  echo "Caught an exception: ",  $err->getMessage();
  /* This data can be logged here that the file is not being opened for some reason. */

echo "The program execution continues."

Since the file does not exist, it will throw an exception, and further programs will execute without dependency on the file.


Caught an exception: error: The required file is missing.
The program execution continues.

Following are some of the functions that can be used:

  • getMessage() − Prints exception message.
  • getCode() −Prints exception code.
  • getFile() − Prints source filename.
  • getLine() − Prints source line.
  • getTrace() − Prints n-array of the backtrace().
  • getTraceAsString() − Prints the formatted string of trace.

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram