CodesCompiler
🔍
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact 🚀 Get Started Free

PHP - Error Handling

PHP - Error Handling

Error handling in PHP refers to the making a provision in PHP code to effectively identifying and recovering from runtime errors that the program might come across. In PHP, the errors are handled with the help of −

  • The die() function
  • The Error Handler Function

The die() Function

The die() function is an alias of exit() in PHP. Both result in termination of the current PHP script when encountered. An optional string if specified in the parenthesis, will be output before the program terminates.

PHP CODE
die("message");

Example

The following code is a typical usage of die() in a PHP script. It displays the File not found message if PHP doesnt find a file, otherwise proceeds to open it for subsequent processing.

PHP CODE
<?php
   if(!file_exists("nosuchfile.txt")) {
      die("File not found");
   } else {
      $file = fopen("nosuchfile","r");
      print "Opend file sucessfully";
	  
      // Rest of the code here.
      fclose($file);
   }
?>

It will produce the followingoutput−

PHP CODE
File not found

Using above technique, you can stop your program whenever it errors out and display more meaningful and user friendly message, rather than letting PHP generate fatal error message.

The Error Handler Function

Using die() for error handling is considered an ungainly and poor program design, as it results in an ugly experience for site users. PHP offers a more elegant alternative with which you can define a custom function and nominate it for handling the errors.

The set_error_handler() function has the following parameters −

PHP CODE
set_error_handler(?callable $callback, int $error_levels = E_ALL): ?callable

The first parameter is a user defined function which is called automatically whenever an error is encountered.

The custom error handler callback function should have the following parameters −

PHP CODE
handler(
   int $errno,
   string $errstr,
   string $errfile = ?,
   int $errline = ?,
   array $errcontext = ?
): bool

Parameters

ParameterImportanceDescriptionerrnoRequiredIt specifies the error level for the user-defined error. It must be numerical value.errstrRequiredIt specifies the error message for the user-defined error.errfileOptionalIt specifies the filename in which the error occurred.errlineOptionalIt specifies the line number at which the error occurred.errcontextOptionalIt specifies an array containing variables and their values in use when the error occurred.

If the callback function returns false, the default error will be called.

The$errnois an integer corresponding to the predefined error levels.

Sr.NoConstant & DescriptionValue1E_ERROR(int)Fatal run-time errors that can not be recovered from. Execution of the script is halted.12E_WARNING(int)Run-time warnings (non-fatal errors). Execution of the script is not halted.23E_PARSE(int)Compile-time parse errors. Parse errors should only be generated by the parser.44E_NOTICE(int)Run-time notices. Something that could indicate an error, but could also happen in the normal course of running a script.85E_CORE_ERROR(int)Fatal errors that occur during PHP’s initial startup. This is like anE_ERROR166E_CORE_WARNING(int)Warnings (non-fatal errors) that occur during PHP’s initial startup. This is like anE_WARNING,327E_COMPILE_ERROR(int)Fatal compile-time errors. This is like anE_ERROR.648E_COMPILE_WARNING(int)Compile-time warnings (non-fatal errors). This is like anE_WARNING.1289E_USER_ERROR(int)User-generated error message. This is like anE_ERROR, generated in PHP code by using the PHP function trigger_error().25610E_USER_WARNING(int)User-generated warning message. This is like anE_WARNING, generated in PHP code by using the function trigger_error().51211E_USER_NOTICE(int)User-generated notice message. This is like anE_NOTICEgenerated in PHP code by using the function trigger_error().102412E_STRICT(int)Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.204813E_RECOVERABLE_ERROR(int)Catchable fatal error. If the error is not caught by a user defined handler, the application aborts as it was anE_ERROR.409614E_DEPRECATED(int)Run-time notices. Enable this to receive warnings about code that will not work in future versions.819215E_USER_DEPRECATED(int)User-generated warning message. This is like anE_DEPRECATED, generated in PHP code by using the function trigger_error().1638416E_ALL(int)All errors, warnings, and notices.32767

Example

Take a look at the following example −

PHP CODE
<?php
   error_reporting(E_ERROR);

   function myerrorhandler($errno, $errstr) {
      echo "error No: $errno Error message: $errstr" . PHP_EOL;
      echo "Terminating PHP script"; 
      die();
   }

   set_error_handler("myerrorhandler");

   $f = fopen("nosuchfile.txt", "r");
   echo "file opened successfully";
   // rest of the code
   fclose($f);
?>

It will produce the followingoutput−

PHP CODE
error No: 2 Error message: fopen(nosuchfile.txt): Failed to open stream: No 
such file or directory
Terminating PHP script

PHPs error class hierarchy starts from throwable interface. All the predefined Error classes in PHP are inherited from Error class.

The ArithmeticError Class

TheArithmeticError classis inherited from theError class. This type of error may occur while performing certain mathematical operations such as performing bitwise shift operation by negative amount.

Example

Take a look at the following example −

PHP CODE
<?php
   try {
      $a = 10;
      $b = -3;
      $result = $a << $b;
   } 
   catch (ArithmeticError $e) {
      echo $e->getMessage(); 
   }
?>

It will produce the followingoutput−

PHP CODE
Bit shift by negative number

This error is also thrown when call to intdiv() function results in value such that it is beyond the legitimate boundaries of integer.

Example

Take a look at the following example −

PHP CODE
<?php
   try {
      $a = PHP_INT_MIN;
      $b = -1;
      $result = intdiv($a, $b);
      echo $result;
   } 
   catch (ArithmeticError $e) {
      echo $e->getMessage(); 
   } 
?>

It will produce the followingoutput−

PHP CODE
Division of PHP_INT_MIN by -1 is not an integer

DivisionByZeroError

DivisionByZeroError class is a subclass of ArithmeticError class. This type of error occurs when value of denominator is zero in the division operation.

Example: Modulo by Zero

Take a look at the following example:

PHP CODE
<?php
   try {
      $a = 10;
      $b = 0;
      $result = $a%$b;
      echo $result;
   } 
   catch (DivisionByZeroError $e) {
      echo $e->getMessage(); 
   }
?>

It will produce the followingoutput−

PHP CODE
Modulo by zero

This can also occur when a modulo operator (%) has 0 as second operator, and intdiv() function having second argument as 0.

Example: Division by Zero

Take a look at the following example −

PHP CODE
<?php
   try {
      $a = 10;
      $b = 0;
      $result = $a/$b;
      echo $result;
   } 
   catch (DivisionByZeroError $e) {
      echo $e->getMessage(); 
   }
?>

It will produce the followingoutput−

PHP CODE
Division by zero

ArgumentCountError

PHP parser throws ArgumentCountError when arguments passed to a user defined function or method are less than those in its definition.

Example

Take a look at the following example −

PHP CODE
<?php
   function add($x, $y) {
      return $x+$y;
   }
   try {
      echo add(10);
   }
   catch (ArgumentCountError $e) {
      echo $e->getMessage();
   }
?>

It will produce the followingoutput−

PHP CODE
Too few arguments to function add(), 1 passed in C:\xampp\php\test.php on line 9 and exactly 2 expected

TypeError

This error is raised when actual and formal argument types don’t match, return type doesn’t match the declared returned type.

Example

Take a look at the following example −

PHP CODE
<?php
   function add(int $first, int $second) {
      echo "addition: " . $first + second;
   }

   try {
      add('first', 'second');
   } 
   catch (TypeError $e) {
      echo $e->getMessage(), "";
   }
?>

It will produce the followingoutput−

PHP CODE
add(): Argument #1 ($first) must be of type int, string given, 
   called in /home/cg/root/63814/main.php on line 7

TypeError is also thrown when PHP’s built-in function is passed incorrect number of arguments. However, the “strict_types=1” directive must be set in the beginning.

Example

Take a look at the following example −

PHP CODE
<?php
   declare(strict_types=1);
   try {
      echo pow(100,2,3);
   }
   catch (TypeError $e) {
      echo $e->getMessage(), "";
   }
?>

It will produce the followingoutput−

PHP CODE
pow() expects exactly 2 parameters, 3 given

Exceptions Handling in PHP

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

Lets explain there new keyword related to exceptions.

  • Try− A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”.
  • Throw− This is how you trigger an exception. Each “throw” must have at least one “catch”.
  • Catch− A “catch” block retrieves an exception and creates an object containing the exception information.

When an exception is thrown, code following 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 (“catched”) within PHP. Code may be surrounded in a try block.
  • Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.
  • Exceptions can be thrown (or re-thrown) within a catch block.

Example

Following is the piece of code, copy and paste this code into a file and verify the result.

PHP CODE
<?php
   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(), "";
   }
   
   // Continue execution
   echo 'Hello World';
?>

In the above example $e->getMessage function is used to get error message. There are following functions which can be used fromExceptionclass.

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

Creating Custom Exception Handler

You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

PHP CODE
string set_exception_handler ( callback $exception_handler )

Hereexception_handleris the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

Example

Take a look at the following example −

PHP CODE
<?php
   function exception_handler($exception) {
      echo "Uncaught exception: " , $exception->getMessage(), "\n";
   }
	
   set_exception_handler('exception_handler');
   throw new Exception('Uncaught Exception');
   
   echo "Not Executed";
?>

Check complete set of error handling functions atPHP Error Handling Functions