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 Error exception can be caught by a 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 the exception handling function has not been registered, it will be handled in the traditional way: it will be reported as a fatal error (Fatal Error). (Recommended learning: PHP Video Tutorial)
The Error class is not extended from the Exception class, so code like catch (Exception $e) { ... } cannot be caught. to Error. You can use code like catch (Error $e) { ... } or register an exception handler (set_exception_handler()) to catch Error.
Error Exception Hierarchy
##Instance
<?php 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(); print($mathOperationsObj->doOperation()); ?>
The execution output of the above program is:
Modulo by zero
The above is the detailed content of How to throw exception in php7. For more information, please follow other related articles on the PHP Chinese website!