Home >Backend Development >PHP Tutorial >PHP exception handling: understanding the properties and methods of exception objects

PHP exception handling: understanding the properties and methods of exception objects

PHPz
PHPzOriginal
2024-06-05 09:15:57277browse

PHP exception object provides important exception information. Its properties include: error message (getMessage()), error code (getCode()), exception file path (getFile()), exception file line number (getLine()), and previous exception (getPrevious()). Its methods include: convert to string (__toString()), obtain call stack (getTrace(), getTraceAsString()).

PHP exception handling: understanding the properties and methods of exception objects

PHP exception handling: understanding the properties and methods of exception objects

In PHP, exception objects provide information about exception events. Important information. By accessing the properties and methods of the exception object, developers can obtain detailed information about the error type, error message, and exception stack trace.

Properties

  • getMessage(): Returns the exception message.
  • getCode(): Returns the exception code (if any).
  • getFile(): Returns the file path where the exception occurred.
  • getLine(): Returns the file line number where the exception occurred.
  • getPrevious(): Returns the previous exception (if any) that caused the current exception.

Method

  • __toString(): Returns the string representation of the exception object, including message, file and line Number.
  • getTrace(): Returns an array containing call stack details.
  • getTraceAsString(): Returns the string representation of the call stack.

Practical case

The following code example demonstrates how to use the properties and methods of the exception object:

<?php

try {
    throw new Exception('自定义异常');
} catch (Exception $e) {
    echo '异常消息:' . $e->getMessage() . PHP_EOL;
    echo '异常代码:' . $e->getCode() . PHP_EOL;
    echo '异常文件:' . $e->getFile() . PHP_EOL;
    echo '异常行号:' . $e->getLine() . PHP_EOL;

    $trace = $e->getTrace();
    echo '调用堆栈:' . PHP_EOL;
    foreach ($trace as $item) {
        echo '    方法:' . $item['function'] . PHP_EOL;
        echo '    文件:' . $item['file'] . PHP_EOL;
        echo '    行号:' . $item['line'] . PHP_EOL;
    }
}
?>

Output:

异常消息:自定义异常
异常代码:0
异常文件:test.php
异常行号:10
调用堆栈:
    方法:main
    文件:test.php
    行号:15

The above is the detailed content of PHP exception handling: understanding the properties and methods of exception objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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