Easy Tutorial
❮ Func Ftp Fput Func Ftp Get Option ❯

PHP 7 Error Handling

PHP 7 New Features

PHP 7 changes the way most errors are reported. Unlike the traditional error reporting mechanism in PHP 5, most errors are now thrown as Error exceptions.

These Error exceptions can be caught by try/catch blocks just like regular exceptions. If no matching try/catch block is found, the exception handler (registered with set_exception_handler()) is called. If no exception handler is registered, the error is handled in the traditional way: reported as a fatal error (Fatal Error).

The Error class does not extend from the Exception class, so code like catch (Exception $e) { ... } will not catch Errors. You can use catch (Error $e) { ... } or register an exception handler (set_exception_handler()) to catch Errors.

Error Exception Hierarchy

-

-

-

-

-

-

-

-

Example

<?php
class MathOperations 
{
   protected $n = 10;

   // Modulo operation with divisor 0, throws exception
   public function doOperation(): string
   {
      try {
         $value = $this->n % 0;
         return $value;
      } catch (DivisionByZeroError $e) {
         return $e->getMessage();
      }
   }
}

$mathOperationsObj = new MathOperations();
print($mathOperationsObj->doOperation());
?>

The above program execution output is:

Modulo by zero

PHP 7 New Features

❮ Func Ftp Fput Func Ftp Get Option ❯