Home > Backend Development > PHP Problem > How to throw exception in php7

How to throw exception in php7

(*-*)浩
Release: 2023-02-26 14:32:01
Original
3902 people have browsed it

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());
?>
Copy after login

The execution output of the above program is:

Modulo by zero
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template