Home > Backend Development > PHP Tutorial > Detailed explanation of error handling and exception handling methods based on PHP7

Detailed explanation of error handling and exception handling methods based on PHP7

jacklove
Release: 2023-04-02 08:40:01
Original
1595 people have browsed it

The editor below will share with you an article based on PHP7 error handling and exception handling methods (detailed explanation), which has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look

PHP7 error handling

PHP 7 has changed the way most errors are reported. Unlike the traditional (PHP 5) error reporting mechanism, most errors are now thrown as Error exceptions.

This Error exception can be caught by the first matching try / catch block just like the Exception exception. If there is no matching catch block, the exception handling function (previously registered through 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 inherit from the Exception class, so you cannot use catch (Exception e)... to catch Error. You can use catch(Errore) { ... }, or catch Error by registering an exception handling function (set_exception_handler()).

Error Hierarchy

Throwable
 Error
  ArithmeticError
   pisionByZeroError
  AssertionError
  ParseError
  TypeError
 Exception
  ...
Copy after login

try
{
 // Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
 // Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
 // Executed only in PHP 5, will not be reached in PHP 7
}
up
down
9
lubaev dot ka at gmail dot com ¶
11 months ago
php 7.1
try {
 // Code that may throw an Exception or ArithmeticError.
} catch (ArithmeticError | Exception $e) {
 // pass
}
Copy after login

Extend (extend) PHP's built-in exception handling class

Users can extend PHP's built-in exception handling class with a custom exception handling class. The following code illustrates which properties and methods in the built-in exception handling class are accessible and inherited by subclasses.

Example #1 Built-in exception handling class

<?php
class Exception
{
 protected $message = &#39;Unknown exception&#39;; // 异常信息
 private $string;       // __toString cache
 protected $code = 0;      // 用户自定义异常代码
 protected $file;       // 发生异常的文件名
 protected $line;       // 发生异常的代码行号
 private $trace;       // backtrace
 private $previous;      // previous exception if nested exception
 public function __construct($message = null, $code = 0, Exception $previous = null);
 final private function __clone();   // Inhibits cloning of exceptions.
 final public function getMessage();  // 返回异常信息
 final public function getCode();   // 返回异常代码
 final public function getFile();   // 返回发生异常的文件名
 final public function getLine();   // 返回发生异常的代码行号
 final public function getTrace();   // backtrace() 数组
 final public function getPrevious();  // 之前的 exception
 final public function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息
 // Overrideable
 public function __toString();    // 可输出的字符串
}
?>
如果使用自定义的类来扩展内置异常处理类,并且要重新定义构造函数的话,建议同时调用 parent::__construct() 来检查所有的变量是否已被赋值。当对象要输出字符串的时候,可以重载 __toString() 并自定义输出的样式。
 Note:
 Exception 对象不能被复制。尝试对 Exception 对象复制 会导致一个 E_ERROR 级别的错误。
Copy after login

<?php
/**
 * 自定义一个异常处理类
 */
class MyException extends Exception
{
 // 重定义构造器使 message 变为必须被指定的属性
 public function __construct($message, $code = 0, Exception $previous = null) {
  // 自定义的代码
  // 确保所有变量都被正确赋值
  parent::__construct($message, $code, $previous);
 }
 // 自定义字符串输出的样式
 public function __toString() {
  return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
 }
 public function customFunction() {
  echo "A custom function for this type of exception\n";
 }
}

/**
 * 创建一个用于测试异常处理机制的类
 */
class TestException
{
 public $var;
 const THROW_NONE = 0;
 const THROW_CUSTOM = 1;
 const THROW_DEFAULT = 2;
 function __construct($avalue = self::THROW_NONE) {
  switch ($avalue) {
   case self::THROW_CUSTOM:
    // 抛出自定义异常
    throw new MyException(&#39;1 is an invalid parameter&#39;, 5);
    break;
   case self::THROW_DEFAULT:
    // 抛出默认的异常
    throw new Exception(&#39;2 is not allowed as a parameter&#39;, 6);
    break;
   default: 
    // 没有异常的情况下,创建一个对象
    $this->var = $avalue;
    break;
  }
 }
}
Copy after login

The above article based on PHP7 error handling and exception handling methods (detailed explanation) is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

Articles you may be interested in:

Explanation of predefined variables for PHP learning

PHP Example of getting the start date and end date of the week of a certain year

PHP interface multi-inheritance and tarits method to achieve multi-inheritance effect_php skills

The above is the detailed content of Detailed explanation of error handling and exception handling methods based on PHP7. For more information, please follow other related articles on the PHP Chinese website!

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