PHP学习三-PHP 7 错误处理

本文详细解析了PHP7中Error与Exception的区别及其层次结构。介绍了如何使用catch/Error处理机制来捕捉不同类型的错误,并提供了实用的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

发现问题: 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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值