📜  PHP |预定义的异常

📅  最后修改于: 2022-05-13 01:56:39.002000             🧑  作者: Mango

PHP |预定义的异常

PHP中提供了预定义异常以更有效地处理异常,但本文的先决条件是学习异常处理 https://www.geeksforgeeks.org/exception-handling-in-php/

异常:此功能在PHP版本 5 和 7 中可用。在版本 7 中,它为每个用户定义的异常提供一个基类,但在版本 5 中,它为每个出现的异常提供一个基类。

Exception 类有 10 个方法和 4 个属性。

这四个属性是——

Short description

data typeFull description
message string The message to be displayed when an exception occurs.
code int The code of the exception when an exception occurs.
file string The name of the file in which exception occurs.
line int The number of the line in which exception occurs.

Exception 中的十个方法是

Function namenumber of argumentsname of argumentsreturn typedescription
__construct 3

message (string)

code (int)

previous(throwtable)

voidan exception is constructed
getMessage0voidstring

returns the message to be displayed when exception occurs

getPrevious 0voidthrowtableprevious exceptions are returned
getCode 0voidmixedThe code for exception generated
getFile0voidstringThe file in which exception occurs in returned
getLine 0voidintThe number line in which exception occurs returned
getTrace0voidarrayThe stack trace is returned
getTraceAsString0voidstringThe stack trace is returned in the form of string
__toString0voidstringThe exception generated is returned in the form of string
__clone0voidvoidThe exception generated is cloned

ErrorException: ErrorException 类只是 Exception 类的扩展版本。它只有一个新添加的属性,其余的都继承自 Exception 类。有两种新的附加方法,一种用于构造异常,另一种用于返回发生的异常的严重性。

额外的一个属性是 -

Short descriptionData typeFull description
severityint

for indicating severity of the exception occurred.

额外的方法是——

Function namenumber of argumentsname of argument return typedescription
__construct6message (string)
code (int)
severity (int)
file name (string)
line number (int)
previous exception (throwtable)
voidan exception is constructed
getSeverity0voidintthe function returns severity of the exception

错误:在PHP中生成的所有内部错误都来自这个基类。它具有类似异常类的功能。它有四个属性和十个方法。函数名称相同,属性都相同。这两个类的区别在于 Exception 类方法返回有关异常的信息,而 Error 类返回有关PHP内部错误的信息。

ArgumentCountError:当预期数量的参数没有作为参数传递给用户定义的函数时,它开始使用。它是 TypeError 类的扩展,所有方法和属性都继承自它。

ArithmeticError:当在PHP中执行算术计算并发生异常时,就会使用这个类。在PHP版本 7 中,当发生此类错误时,也会尝试进行负值位移。该类是Error类的扩展,因此所有方法都是刚刚从Error类继承的属性。

AssertionError:如果已通过函数assert 执行了断言并导致异常,则该类开始使用。函数assert() 用于计算断言,该函数返回一个布尔值。在调试时,此函数是一个有用的功能。

DivisionByZeroError:如果一个数字被零除,则使用此类,它是 ArithmeticError 类的扩展。

CompileError:如果在编译过程中发生错误,那么编译错误发生在哪个类 CompileError 类。通常编译错误是致命错误。此类是 Error 类的扩展。

ParseError:当PHP代码被解析并发生异常时,该类开始使用。它是类 CompileError 的扩展。像 eval() 这样的语言构造函数会生成这种类型的异常。

TypeError:这个类是Error类的扩展。产生此类异常的主要原因有三个。

  • 函数中声明的参数类型与传递的参数类型不匹配。
  • 声明的函数的返回类型与返回的类型不匹配。
  • 有一些内置的PHP函数采用受限和某些类型的参数。如果将错误类型或数量的参数传递给它们,则会发生此异常。