php中的错误和异常是两个不一样的概念。php
错误:是由于脚本的问题,好比少写了分号,调用未定义的函数,除0,等一些编译语法错误。php7
异常:是由于业务逻辑和流程,不符合预期状况,好比验证请求参数,不经过就用 throw new 抛一个异常。函数
在php5的版本中,错误是没法被 try {} catch 捕获的,以下所示:blog
<?php 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()
有些时候,咱们须要捕获这种错误,并作相应的处理。get
那就须要用到 register_shutdown_function() 和 error_get_last() 来捕获错误io
<?php error_reporting(E_ALL); ini_set('display_errors', 'on'); //注册一个会在php停止时执行的函数 register_shutdown_function(function () { //获取最后发生的错误 $error = error_get_last(); if (!empty($error)) { echo $error['message'], '<br>'; echo $error['file'], ' ', $error['line']; } }); hello();
咱们还能够经过 set_error_handler() 把一些Deprecated、Notice、Waning等错误包装成异常,让 try {} catch 可以捕获到。编译
<?php 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 实现了该接口。ast
因此咱们在php7中,能够经过 try {} catch(\Throwable $e) 来捕获php5中没法捕获到的错误。function
<?php error_reporting(E_ALL); ini_set('display_errors', 'on'); try { hello(); } catch (\Throwable $e) { echo $e->getMessage(); }