We now have a youtube channel. Subscribe!

PHP Error and Exception Handling

PHP - Error and Exception Handling

Hello folks! welcome back to a new section of our tutorial on PHP. In this section of our PHP tutorial, we will be studying about PHP Error and Exception Handling.

Error handling can be described as a process of catching errors raised by your program and taking appropriate actions.

It is very easy in PHP to handle errors.

Handling Errors using the die() Function

Whie writing your PHP code you should check all possible error conditions before going ahead and take relevant action where needed.


Try the following example below without having /tmp/text.xt file and with this file -

   if(!file_exists("/tmp/test.txt")) {
      die("File not found");
   }else {
      $file = fopen("/tmp/test.txt","r");
      print "Opend file sucessfully";
   // Test of the code here.

By this way you can write a very efficient code. By making use of above method you can stop your code whenever it errors out and shows more meaningful and user friendly message.

Defining Custom Error Handling Function

You can write your own function to handle any error. PHP gives you a framework to define error handling function.

This PHP function must be able to handle at least a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally : file, line-number, and the error context) -


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

Sr.NoParameter & Description


Required - Specifies the error report level for the user-defined error. Must be a value number.



Required - Specifies the error message for the user-defined error



Optional - Specifies the file name in which the error occurred



Optional - Specifies the line number in which the error occurred



Optional - Specifies an array containing every variable and their values in use when the error occurred

Possible Error Levels

These error report levels are the various types of error that the user defined error handler can be used for. These values can be used in combination with the | operator.

Sr.NoConstant & DescriptionValue


Fatal run-time errors. Execution of the script is halted



Non-fatal run-time errors. Execution of the script is not halted



Compile-time parse errors. Parse errors should only be generated by the parser.



Run-time notices. The script found something that might be an error, but could also happen when running a script normally



Fatal errors that occur during PHP's initial start-up.



Non-fatal run-time errors. This occurs during PHP's initial start-up.



Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()



Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()



User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()



Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.



Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())



All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)


All the above error level can be set using following PHP built-in library function where level can be any of the value that is being defined in the above table.

int error_reporting ( [int $level] )


The following example below is a method you can create one error handling function -

   function handleError($errno, $errstr,$error_file,$error_line) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
      echo "<br />";
      echo "Terminating PHP Script";

Soon as you define your custom error handler, you need to set it by using the PHP built-in library set_error_handler function. Now let us examine our example by calling a function which doesn't exist.

   error_reporting( E_ERROR );
   function handleError($errno, $errstr,$error_file,$error_line) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
      echo "<br />";
      echo "Terminating PHP Script";
   //set error handler
   //trigger error

Exception Handling in PHP

Exception Handling in PHP

PHP has an exception model that is very similar to that of other languages. Exceptions are very important and provides a better control over error handling.

Let us explain some of the new keywords related to exceptions -

  • Try - A function that is using an exception should be in a "try" block. If the exception does not trigger, the code is going to continue as usual. But if the exception triggers, an exception is "thrown".
  • Throw - This is the way that an exception is triggered. A "throw" must have a least a "catch".
  • Catch - A "catch" retrieves an exception and creates an object holding the exception information.

When an exception is thrown in PHP, the code that follows the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an uncaught Exception.

  • An exception can be thrown and caught within PHP. The code may be surrounded in a try block.
  • Each try block must have at least a corresponding catch. Multiple catch blocks can be used for catching different classes of exceptions.
  • Exceptions can be thrown or re-thrown in a catch block.


The following below is a simple example -

   try {
      $error = 'Always throw this error';
      throw new Exception($error);
      // Code following an exception is not executed.
      echo 'Never executed';
   }catch (Exception $e) {
      echo 'Caught exception: ',  $e->getMessage(), "\n";
   // Continue execution
   echo 'Hello World';

In the above example $e->getMessage() is used to get error message. Following below are the functions which can be used from Exception class -

  • getMessage() - Used to get the exception message.
  • getCode() - Used for getting code of the exception.
  • getFile() - Source filename.
  • getLine() - Source line.
  • getTrace - Used to get the n array of the backtrace().
  • getTraceAsString - Used for getting the formatted string of trace.

PHP - Custom Exception Handler

Creating a Custom Exception Handler

In PHP, you can define your own custom exception handler. Use following function in setting a use-defined exception handler function -

string set_exception_handler ( callback $exception_handler )

Here, exception_handler is the name of the function that is to be called upon when an uncaught exception occurs. This function must be defined before calling the set_exception handler().


The following below is a simple example -

   function exception_handler($exception) {
      echo "Uncaught exception: " , $exception->getMessage(), "\n";
   throw new Exception('Uncaught Exception');
   echo "Not Executed\n";

Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we will be discussing about the PHP Bugs Debugging.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain