PHP – Error and Exception Handling

By | October 2, 2021
PHP - Error and Exception Handling

PHP allows you to handle errors that occur during the execution of the program and execute some steps to manage the errors. In order to make your code work properly, you should know how to handle unexpected errors.

die() function

It is smart move to check for all possible errors in advance to avoid big mistakes and take suitable actions if required. This method will stop your program whenever it throws some error and displays some message or information regarding the error.


if(!file_exists("/tmp/first_test.txt")) {
die("File not found");
}else {
$file = fopen("/tmp/first_test.txt","r");
print "success- file open";
// Code

Custom error handling function

PHP supports users to create their own code to handle the error in your way. This function handles two parameters but can take up to five parameters to handle the error in your program.




  • error _level defines the level of the error that occurred and is denoted by a number.
  • Error_message allows you to display the user-defined error message.
  • Error_file specifies the file where the error occurs.
  • Error_line specifies the line number of the error occurred.
  • Error_context is an array that contains variables and their value for the occurred error.

The error level mentioned above in the syntax can have different values depending on the type of error that occurred. Even you can use more than one error value using ‘|’ value. Below is the list of some user-defined error report levels.

Value Constant Description
1 E_ERROR The fatal run-time error which halts the script execution then and there.
2 E_WARNING The non-fatal run-time error which does not halt the script execution.
4 E_PARSE Parser created this compile-time parse error.
8 E_NOTICE When the script finds something that may create an error during run-time.
16 E_CORE_ERROR This fatal error occurs whenever you initial start-up the PHP.
32 E_CORE_WARNING This non-fatal run-time error occurs during the initial start-up of PHP.
256 E_USER_ERROR These are a user-generated fatal error
512 E_USER_WARNING These are a user-generated non-fatal error
1024 E_USER_NOTICE Used with trigger_error() function and is user-generated notice.
2048 E_STRICT It allows you to make changes of the code for forwarding code compatibility and are run-time notices.
4096 E_RECOVERABLE_ERROR This is the fatal error that can be caught.
8191 E_ALL It includes all types of errors except E_STRICT.

You can set error levels using PHP in-built functions-

Int error_reporting ([int $level])

Example of custom error handling

function handleError($errno, $errstr,$error_file,$error_line) {
echo "<b>Error:</b> [$errno] <br>";
echo "Halth the execution of the Script";

Now you have to set this custom error handling using set_error_handler, a PHP built-in function.


error_reporting( E_ERROR );
function handleError($errno, $errstr,$error_file,$error_line) {
echo "<b>Error:</b> [$errno]";
echo "<br />";
echo "terminate the Execution";
//setting an error handler
//triggerring an error

Exception handling in PHP

Run-time exceptions can be handled using PHP keywords. Below is the list of keywords-

  • try- you can put the code within this try block which is expected to throw an error. If there is no error the code will run normally. In case if there is no error then the code will run normally.
  • Throw- this block will trigger an exception and comes along with at least one catch block.
  • Catch- this block will create an object to handle the thrown error.


try {
$error = 'Error is thrown';
throw new Exception($error);
// Code will not executed.
echo 'the code never executed’;
}catch (Exception $exp) {
echo 'Caught exception: ', $exp->getMessage();
// Continue code execution

Exception class comes with various functions, getMessage() is one of them that is used in the above example. Some of the other functions are as below-

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

How to create a custom exception handler

PHP allows you to create your own exception handler with the following syntax-

string set_exception_handler ( callback $exception_handler )

You can call the exception_handler function when an exception occurs but is not caught.


function exception_handler($exp) {
echo "Uncaught exception occurs: " , $exp->getMessage();
throw new Exception('Uncaught Exception Occured');


Uncaught exception occurs: Uncaught Exception Occured

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *