搜索热词
PHP中的错误和异常是两个不同的概念。
错误:是因为脚本的问题,比如少写了分号,调用未定义的函数,除0,等一些编译语法错误。
异常:是因为业务逻辑和流程,不符合预期情况,比如验证请求参数,不通过就用 throw new 抛一个异常。
在PHP5的版本中,错误是无法被 try {} catch 捕获的,如下所示:
error_reporting(E_ALL);
ini_set('display_errors','on');
try {
hello();
} catch (\Exception $e) {
echo $e->getMessage();
}
运行脚本,最终PHP报出一个Fatal error,并程序中止。
Fatal error: Uncaught Error: Call to undefined function hello()
有些时候,我们需要捕获这种错误,并做相应的处理。
那就需要用到 register_shutdown_function() 和 error_get_last() 来捕获错误
error_reporting(E_ALL);
ini_set('display_errors','on');
//注册一个会在PHP中止时执行的函数
register_shutdown_function(function () {
//获取最后发生的错误
$error = error_get_last();
if (!empty($error)) {
echo $error['message'],'
';
echo $error['file'],' ',$error['line'];
}
});
hello();
我们还可以通过 set_error_handler() 把一些Deprecated、Notice、Waning等错误包装成异常,让 try {} catch 能够捕获到。
error_reporting(E_ALL);
ini_set('display_errors','on');
//捕获Deprecated、Notice、Waning级别错误
set_error_handler(function ($errno,$errstr,$errfile) {
throw new \Exception($errno . ' : ' . $errstr . ' : ' . $errfile);
//返回true,表示错误处理不会继续调用
return true;
});
try {
$data = [];
echo $data['index'];
} catch (\Exception $e) {
//捕获Notice: Undefined index
echo $e->getMessage();
}
对于PHP7中的错误捕获,因为PHP7中定义了 Throwable 接口,大部分的 Error 和 Exception 实现了该接口。
所以我们在PHP7中,可以通过 try {} catch(\Throwable $e) 来捕获PHP5中无法捕获到的错误。
error_reporting(E_ALL);
ini_set('display_errors','on');
try {
hello();
} catch (\Throwable $e) {
echo $e->getMessage();
}
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。