Home  >  Article  >  Backend Development  >  How to throw exception in php7

How to throw exception in php7

(*-*)浩
(*-*)浩Original
2019-10-14 10:32:353805browse

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.

How to throw exception in php7

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

How to throw exception in php7

##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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn