PHP 7 Error Handling

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

This kind of Error exception can be caught by try / catch block like a normal exception. If there is no matching try / catch block, the exception handling function (registered by set_exception_handler()) is called for processing. If an exception handler has not been registered, it is handled in the traditional way: it is reported as a Fatal Error.

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

Error Exception Hierarchy

  • Error
    • ArithmeticError
    • AssertionError
    • DivisionByZeroError
    • ParseError
    • ##TypeError
  • ##Exception
    • ...
class MathOperations 
   protected $n = 10;
   // 求余数运算,除数为 0,抛出异常
   public function doOperation(): string
      try {
         $value = $this->n % 0;
         return $value;
      } catch (DivisionByZeroError $e) {
         return $e->getMessage();
$mathOperationsObj = new MathOperations();

The execution output of the above program is:

Modulo by zero

Next Section