您的位置:首页 > 编程语言 > PHP开发

PHP学习三-PHP 7 错误处理

2018-03-31 15:58 204 查看
1.Error 层次结构
示例

2.Exception类定义
示例

发现问题: PHP7的异常通过
try{}catch(){}
无法抓取到。

查看手册发现:不同于传统(PHP 5)的错误报告机制,现在大多数错误被作为 Error 异常抛出。

Error
类并非继承自
Exception
类,所以不能用
catch (Exception $e) { ... }
来捕获
Error
。你可以用
catch (Error $e) { ... }
,或者通过注册异常处理函数(
set_exception_handler()
)来捕获
Error


1.Error 层次结构

Throwable

Exception

Error

ArithmeticError

DivisionByZeroError

AssertionError

ParseError

TypeError

示例

#php 7.1
try {
$result = eval("return 1+k;");
} catch (Throwable $e) {   //此处通过Exception是无法抓取到错误的
//do sth
}


2.Exception类定义

Exception {
/* 属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 方法 */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Throwable getPrevious ( void )
final public int getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
}


示例

抓取异常后,排查问题比较有用的方法

try {
} catch(Exception $e) {
//查看错误抛出时的调用栈
print_r($e->getTrace());
//查看异常所在文件及行数
print_r($e->getFile().$e->getLine());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: