Php 简明教程

PHP – Exceptions

在 7 之前的版本中,PHP 解析器在响应各种条件时曾经报告错误。每个错误曾经都是一个预定义类型。PHP7 已经更改了错误报告的机制。与传统的错误报告不同,现在大多数错误都是通过抛出错误异常来报告的。

Prior to version 7, PHP parser used to report errors in response to various conditions. Each error used to be of a certain predefined type. PHP7 has changed the mechanism of error reporting. Instead of traditional error reporting, most errors are now reported by throwing error exceptions.

PHP 中的异常处理机制与许多其他语言类似,并且使用 try, catch, throwfinally 关键字实现。

The exception handling mechanism in PHP is similar to many other languages, and is implemented with the try, catch, throw and finally keywords.

The Throwable Interface

PHP 中的异常实现了 Throwable interface 。Throwable 接口充当任何可通过 throw 语句引发对象的基类,包括 Error 和 Exception 对象。

Exceptions in PHP implements the Throwable interface. The Throwable interface acts as the base for any object that can be thrown via throw statement, including Error and Exception objects.

用户定义的类不能直接实现 Throwable 接口。相反,要声明一个用户定义的异常类,必须扩展 Exception class

A user defined class cannot implement Throwable interface directly. Instead, to declare a user defined exception class, it must extend the Exception class.

带有潜在异常的 PHP 代码被 try 块包围。如果找到异常对象,则抛出该对象,以方便捕获潜在的异常。每个 try 必须至少有一个对应的 catchfinally 块。此外,对应于 try 块可能有多个 catch/finally 块。

PHP code with potential exceptions is surrounded in a try block. An exception object is thrown if it is found, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block. Moreover, there may be more than one catch/finally blocks corresponding to a try block.

try {

   // throw errors in the try-block
   // if an error occurs we can throw an exception
   throw new Exception('this is an error.');
}
catch(Exception $e) {

   // catch the throws in the catch-block
   // do something with the exception object, eg.
   // display its message
   echo 'Error message: ' .$e->getMessage();
}

如果抛出了异常并且没有 catch 块,那么异常会“冒泡”出现,直到找到一个匹配的 catch 块。如果调用堆栈一直向下绕回到全局范围而没有遇到一个匹配的 catch 块,那么将调用一个全局异常处理程序(如果已设置),否则程序将以一个致命错误终止。

If an exception is thrown and there is no catch block, the exception will "bubble up" until it finds a matching catch block. If the call stack is unwound all the way to the global scope without encountering a matching catch block, a global exception handler will be called (if it is set) otherwise the program will terminate with a fatal error.

set_exception_handler

如果异常没有在 try/catch 块中被捕获,则此函数将设置默认异常处理程序。在回调函数执行之后,程序执行将停止。

This function sets the default exception handler if an exception is not caught within a try/catch block. After the callback is executed, the program execution will stop.

set_exception_handler(?callable $callback): ?callable

当一个未捕获的异常发生时,$callback 参数是要被调用的函数的名称。在调用 set_exception_handler() 之前必须定义此函数。此处理程序函数需要接受一个参数,该参数将是抛出的异常对象。

The $callback parameter is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

此函数将返回以前定义的异常处理程序的名称,或者在出错时返回 NULL。如果之前没有定义处理程序,那么也将返回 NULL。

The function returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

Example

请看以下示例:

Take a look at the following example −

<?php
   function handler($ex) {
      echo "Uncaught exception is : " , $ex->getMessage(), "\n";
   }

   set_exception_handler('handler');
   throw new Exception('Not Found Exception');
   echo "not included Executed\n";
?>

它将生成以下 output

It will produce the following output

Uncaught exception is : Not Found Exception

SPL Exceptions

标准 PHP 库包含预定义的异常 −

Standard PHP library contains predefined exceptions −

Sr.No

Predefined Exceptions

1

LogicException Exception that represents error in the program logic.

2

BadFunctionCallException Exception thrown if a callback refers to an undefined function or if some arguments are missing.

3

BadMethodCallException Exception thrown if a callback refers to an undefined method or if some arguments are missing.

4

DomainException Exception thrown if a value does not adhere to a defined valid data domain.

5

InvalidArgumentException Exception thrown if an argument is not of the expected type.

6

LengthException Exception thrown if a length is invalid.

7

OutOfRangeException Exception thrown when an illegal index was requested.

8

RuntimeException Exception thrown if an error which can only be found on runtime occurs.

9

OutOfBoundsException Exception thrown if a value is not a valid key.

10

OverflowException Exception thrown when adding an element to a full container.

11

RangeException Exception thrown to indicate range errors during program execution. An arithmetic error other than under/overflow.

12

UnderflowException Exception thrown when performing an invalid operation on an empty container, such as removing an element.

13

UnexpectedValueException Exception thrown if a value does not match with a set of values.

User-defined Exception

你可以定义一个扩展了基本 Exception 类的自定义异常类。下面的脚本定义了一个称为 myException 的自定义异常类。如果 $num 的值小于 0 或者大于 100,则会抛出此类型的异常。

You can define a custom exception class that extends the base Exception class. Following script defines a custom exception class called myException. This type of exception is thrown if value of $num is less than 0 or greater than 100.

Example

Exception 类的 getMessage() 方法返回错误消息,而 getLine() 方法返回出现异常的代码行。

The getMessage() method of Exception class returns the error message and getLine() method returns line of code in which exception appears.

<?php
   class myException extends Exception {
      function message() {
         return "error : ". $this->getMessage(). "in line no". $this->getLine();
      }
   }
   $num=125;
   try {
      if ($num>100 || $num<0)
      throw new myException("$num is invalid number");
      else
      echo "$num is a valid number";
   }
   catch (myException $m) {
      echo $m->message();
   }
?>

使用 $num=125$num=90 运行上述代码,可获得一条错误消息和一条有效的数字消息 −

Run the above code with $num=125 and $num=90 to get an error message and a message of valid number −

error : 125 is invalid number in line no 10