<?php
$filename = 'test.txt';
try {
if (!file_exists($filename)) {
throw new Exception('文件不存在');
}
} catch(Exception $e) {
echo $e->getMessage();
}
Exception 是所有异常的基类
基本属性
message 异常消息内容
code 异常代码
file 抛出异常的文件名
line 抛出异常在该文件的行数
常用方法
getTrace 获取异常追踪信息
getTraceAsString 获取异常追踪信息的字符串
getMessage 获取出错信息
<?php
class MyException extends Exception {
function getInfo() {
return '自定义错误信息';
}
}
try {
throw new MyException('error');
} catch(Exception $e) {
echo $e->getInfo();
}