Throwable
(PHP 7, PHP 8)
简介
PHP 7 里,Throwable 是能被 throw
语句抛出的最基本的接口(interface),包含了 Error 和 Exception。
注意:
PHP 类无法直接实现 (implement) Throwable 接口,而应当去继承 Exception。
接口摘要
Throwable {
/* 方法 */
}
目录
- Throwable::getMessage — 获取信息
- Throwable::getCode — 获取异常代码
- Throwable::getFile — 获取创建对象的文件
- Throwable::getLine — 获取初始化对象时候的行号
- Throwable::getTrace — 获取堆栈踪迹(Stack Trace)
- Throwable::getTraceAsString — 说明
- Throwable::getPrevious — 返回先前的 Throwable
- Throwable::__toString — 获取 Throwable 对象 string 形式的表达
用户贡献的笔记
mlocati at gmail dot com
I wrote a simple script that prints out the Throwable and Exception tree for every PHP version.
You can find this script here:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
And its output is here:
https://3v4l.org/sDMsv
thisbug at foxmail dot com
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5.x
} catch (Exception $e) {
// Executed only in PHP 5.x, will not be reached in PHP 7
}
interface MyPackageThrowable extends Throwable {}
class MyPackageException extends Exception implements MyPackageThrowable {}
throw new MyPackageException();
转载请注明:悠然品鉴 » PHP Throwable 用法 手册 | 示例代码