Php 简明教程

PHP - Error Handling

在 PHP 中处理错误是指在 PHP 代码中做出规定来有效识别和恢复程序可能遇到的运行时错误。在 PHP 中,错误的处理方法有 -

Error handling in PHP refers to the making a provision in PHP code to effectively identifying and recovering from runtime errors that the program might come across. In PHP, the errors are handled with the help of −

  1. The die() function

  2. The Error Handler Function

The die() Function

die() 函数是 PHP 中 exit() 的别名。当遇到它们时,这两个函数都会导致当前 PHP 脚本终止。如果在括号中指定了一个可选字符串,它将在程序终止前输出。

The die() function is an alias of exit() in PHP. Both result in termination of the current PHP script when encountered. An optional string if specified in the parenthesis, will be output before the program terminates.

die("message");

Example

以下代码是 die() 在 PHP 脚本中的典型用法。如果 PHP 找不到文件,它将显示“File not found”消息,否则它会继续将其打开以进行后续处理。

The following code is a typical usage of die() in a PHP script. It displays the File not found message if PHP doesn’t find a file, otherwise proceeds to open it for subsequent processing.

<?php
   if(!file_exists("nosuchfile.txt")) {
      die("File not found");
   } else {
      $file = fopen("nosuchfile","r");
      print "Opend file sucessfully";

      // Rest of the code here.
      fclose($file);
   }
?>

它将生成以下 output

It will produce the following output

File not found

使用上述技术,当您的程序发生错误时,您可以随时停止程序并显示更具意义且用户友好的消息,而不是让 PHP 生成致命错误消息。

Using above technique, you can stop your program whenever it errors out and display more meaningful and user friendly message, rather than letting PHP generate fatal error message.

The Error Handler Function

使用 die() 处理错误被认为是一种笨拙且糟糕的程序设计,因为它会导致网站用户的体验很差。PHP 提供了一个更优雅的替代方法,您可以使用它定义一个自定义函数并指定它来处理错误。

Using die() for error handling is considered an ungainly and poor program design, as it results in an ugly experience for site users. PHP offers a more elegant alternative with which you can define a custom function and nominate it for handling the errors.

set_error_handler() 函数具有以下参数 -

The set_error_handler() function has the following parameters −

set_error_handler(?callable $callback, int $error_levels = E_ALL): ?callable

第一个参数是用户定义的函数,每当遇到错误时都会自动调用该函数。

The first parameter is a user defined function which is called automatically whenever an error is encountered.

自定义错误处理回调函数应具有以下参数 -

The custom error handler callback function should have the following parameters −

handler(
   int $errno,
   string $errstr,
   string $errfile = ?,
   int $errline = ?,
   array $errcontext = ?
): bool

Parameters

Parameter

Importance

Description

errno

Required

It specifies the error level for the user-defined error. It must be numerical value.

errstr

Required

It specifies the error message for the user-defined error.

errfile

Optional

It specifies the filename in which the error occurred.

errline

Optional

It specifies the line number at which the error occurred.

errcontext

Optional

It specifies an array containing variables and their values in use when the error occurred.

如果回调函数返回 false,将调用默认错误。

If the callback function returns false, the default error will be called.

$errno 是一个对应于预定义错误级别的整数。

The $errno is an integer corresponding to the predefined error levels.

Sr.No

Constant & Description

Value

1

E_ERROR (int) Fatal run-time errors that can not be recovered from. Execution of the script is halted.

1

2

E_WARNING (int) Run-time warnings (non-fatal errors). Execution of the script is not halted.

2

3

E_PARSE (int) Compile-time parse errors. Parse errors should only be generated by the parser.

4

4

E_NOTICE (int) Run-time notices. Something that could indicate an error, but could also happen in the normal course of running a script.

8

5

E_CORE_ERROR (int) Fatal errors that occur during PHP’s initial startup. This is like an E_ERROR

16

6

E_CORE_WARNING (int) Warnings (non-fatal errors) that occur during PHP’s initial startup. This is like an E_WARNING,

32

7

E_COMPILE_ERROR (int) Fatal compile-time errors. This is like an E_ERROR.

64

8

E_COMPILE_WARNING (int) Compile-time warnings (non-fatal errors). This is like an E_WARNING.

128

9

E_USER_ERROR (int) User-generated error message. This is like an E_ERROR, generated in PHP code by using the PHP function trigger_error().

256

10

E_USER_WARNING (int) User-generated warning message. This is like an E_WARNING, generated in PHP code by using the function trigger_error().

512

11

E_USER_NOTICE (int) User-generated notice message. This is like an E_NOTICE generated in PHP code by using the function trigger_error().

1024

12

E_STRICT (int) Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

2048

13

E_RECOVERABLE_ERROR (int) Catchable fatal error. If the error is not caught by a user defined handler, the application aborts as it was an E_ERROR.

4096

14

E_DEPRECATED (int) Run-time notices. Enable this to receive warnings about code that will not work in future versions.

8192

15

E_USER_DEPRECATED (int) User-generated warning message. This is like an E_DEPRECATED, generated in PHP code by using the function trigger_error().

16384

16

E_ALL (int) All errors, warnings, and notices.

32767

Example

请看以下示例:

Take a look at the following example −

<?php
   error_reporting(E_ERROR);

   function myerrorhandler($errno, $errstr) {
      echo "error No: $errno Error message: $errstr" . PHP_EOL;
      echo "Terminating PHP script";
      die();
   }

   set_error_handler("myerrorhandler");

   $f = fopen("nosuchfile.txt", "r");
   echo "file opened successfully";
   // rest of the code
   fclose($f);
?>

它将生成以下 output

It will produce the following output

error No: 2 Error message: fopen(nosuchfile.txt): Failed to open stream: No
such file or directory
Terminating PHP script

PHP 的错误类层次结构始于 throwable 接口。PHP 中所有预定义的 Error 类都继承自 Error 类。

PHP’s error class hierarchy starts from throwable interface. All the predefined Error classes in PHP are inherited from Error class.

The ArithmeticError Class

ArithmeticError class 继承自 Error class 。在执行某些数学运算(例如以负数执行按位移位运算)时,可能会发生这种类型的错误。

The ArithmeticError class is inherited from the Error class. This type of error may occur while performing certain mathematical operations such as performing bitwise shift operation by negative amount.

Example

请看以下示例:

Take a look at the following example −

<?php
   try {
      $a = 10;
      $b = -3;
      $result = $a << $b;
   }
   catch (ArithmeticError $e) {
      echo $e->getMessage();
   }
?>

它将生成以下 output

It will produce the following output

Bit shift by negative number

当调用 intdiv() 函数导致的值超出整数的合法边界时,也会引发此错误。

This error is also thrown when call to intdiv() function results in value such that it is beyond the legitimate boundaries of integer.

Example

请看以下示例:

Take a look at the following example −

<?php
   try {
      $a = PHP_INT_MIN;
      $b = -1;
      $result = intdiv($a, $b);
      echo $result;
   }
   catch (ArithmeticError $e) {
      echo $e->getMessage();
   }
?>

它将生成以下 output

It will produce the following output

Division of PHP_INT_MIN by -1 is not an integer

DivisionByZeroError

DivisionByZeroError 类是 ArithmeticError 类的子类。当除法运算中的分母值为零时,会发生此类型的错误。

DivisionByZeroError class is a subclass of ArithmeticError class. This type of error occurs when value of denominator is zero in the division operation.

Example: Modulo by Zero

来看一下以下示例:

Take a look at the following example:

<?php
   try {
      $a = 10;
      $b = 0;
      $result = $a%$b;
      echo $result;
   }
   catch (DivisionByZeroError $e) {
      echo $e->getMessage();
   }
?>

它将生成以下 output

It will produce the following output

Modulo by zero

当模运算符(%)的第二个运算符为 0,且 intdiv() 函数的第二个参数为 0 时,也会发生这种情况。

This can also occur when a modulo operator (%) has 0 as second operator, and intdiv() function having second argument as 0.

Example: Division by Zero

请看以下示例:

Take a look at the following example −

<?php
   try {
      $a = 10;
      $b = 0;
      $result = $a/$b;
      echo $result;
   }
   catch (DivisionByZeroError $e) {
      echo $e->getMessage();
   }
?>

它将生成以下 output

It will produce the following output

Division by zero

ArgumentCountError

当传递给用户定义函数或方法的参数少于其定义中的参数时,PHP 解析器会引发 ArgumentCountError。

PHP parser throws ArgumentCountError when arguments passed to a user defined function or method are less than those in its definition.

Example

请看以下示例:

Take a look at the following example −

<?php
   function add($x, $y) {
      return $x+$y;
   }
   try {
      echo add(10);
   }
   catch (ArgumentCountError $e) {
      echo $e->getMessage();
   }
?>

它将生成以下 output

It will produce the following output

Too few arguments to function add(), 1 passed in C:\xampp\php\test.php on line 9 and exactly 2 expected

TypeError

当实际参数类型和形式参数类型不匹配、返回类型不匹配声明的返回类型时,会引发此错误。

This error is raised when actual and formal argument types don’t match, return type doesn’t match the declared returned type.

Example

请看以下示例:

Take a look at the following example −

<?php
   function add(int $first, int $second) {
      echo "addition: " . $first + second;
   }

   try {
      add('first', 'second');
   }
   catch (TypeError $e) {
      echo $e->getMessage(), "";
   }
?>

它将生成以下 output

It will produce the following output

add(): Argument #1 ($first) must be of type int, string given,
   called in /home/cg/root/63814/main.php on line 7

当 PHP 的内置函数传递的参数数量不正确时,也会引发 TypeError。但是,必须一开始就设置“strict_types=1”指令。

TypeError is also thrown when PHP’s built-in function is passed incorrect number of arguments. However, the "strict_types=1" directive must be set in the beginning.

Example

请看以下示例:

Take a look at the following example −

<?php
   declare(strict_types=1);
   try {
      echo pow(100,2,3);
   }
   catch (TypeError $e) {
      echo $e->getMessage(), "";
   }
?>

它将生成以下 output

It will produce the following output

pow() expects exactly 2 parameters, 3 given

Exceptions Handling in PHP

PHP 具有一个类似于其他编程语言的异常模型。异常很重要,并提供了对错误处理的更好控制。

PHP has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.

让我们解释一下与异常相关的新的关键字。

Lets explain there new keyword related to exceptions.

  1. Try − A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".

  2. Throw − This is how you trigger an exception. Each "throw" must have at least one "catch".

  3. Catch − A "catch" block retrieves an exception and creates an object containing the exception information.

当抛出异常时,语句后面的代码不会执行,并且 PHP 将尝试查找第一个匹配的 catch 块。如果未捕获异常,则会使用“未捕获异常”发出 PHP 致命错误……

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception …​

  1. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block.

  2. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.

  3. Exceptions can be thrown (or re-thrown) within a catch block.

Example

以下是代码片,复制并将此代码粘贴到文件中并验证结果。

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
   try {
      $error = 'Always throw this error';
      throw new Exception($error);

      // Code following an exception is not executed.
      echo 'Never executed';
   }catch (Exception $e) {
      echo 'Caught exception: ',  $e->getMessage(), "";
   }

   // Continue execution
   echo 'Hello World';
?>

在上面的示例中,$e→getMessage 函数用于获取错误消息。有以下函数可以从 Exception 类中使用。

In the above example $e→getMessage function is used to get error message. There are following functions which can be used from Exception class.

  1. getMessage() − message of exception

  2. getCode() − code of exception

  3. getFile() − source filename

  4. getLine() − source line

  5. getTrace() − n array of the backtrace()

  6. getTraceAsString() − formated string of trace

Creating Custom Exception Handler

您可以定义您自己的自定义异常处理程序。使用以下函数设置用户定义的异常处理程序函数。

You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

string set_exception_handler ( callback $exception_handler )

这里 exception_handler 是在发生未捕获异常时要调用的函数的名称。必须在调用 set_exception_handler() 之前定义此函数。

Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

Example

请看以下示例:

Take a look at the following example −

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

   set_exception_handler('exception_handler');
   throw new Exception('Uncaught Exception');

   echo "Not Executed";
?>

PHP Error Handling Functions 查看错误处理函数的完整列表

Check complete set of error handling functions at PHP Error Handling Functions