Home >Backend Development >PHP Tutorial >PHP exception handling: understanding the properties and methods of exception objects
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
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
Method
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!