一、绪

首先明确一点:异常和错误不是一回事。

一个异常(Exception)是一个程序执行过程中出现的一个例外或是一个事件,它中断了正常指令的运行,跳转到其他程序模块继续执行。

基本格式:

try {
    // 进行异常检测的代码部分,比如 throw new Exception('手动抛出异常');      
} catch (Exception $e) {
    // 进行异常捕获处理
} finally {
    // 不管有没异常都会执行   
}

说明:

  • try...catch... 一个try至少对应一个catch,也不能单独出现catch
  • PHP中,异常需要手动抛出
  • throw关键字将出发异常处理机制,是一个语句结构,必须给它传递一个对象作为值
  • 抛出的异常会被对应的catch捕获

二、扩展内置的Exception类

<?php
class 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 getMessage ( void ) : string
    // 返回异常编号
    final public getCode ( void ) : int
    // 返回发生异常的文件名
    final public getFile ( void ) : string
    // 返回发生异常的代码行号
    final public getLine ( void ) : int
    final public getTrace ( void ) : array
    // 已经格式化成字符串的 getTrace() 信息
    final public getTraceAsString ( void ) : string

    // 可输出对象信息
    public __toString ( void ) : string
}

Exception 基类详见: https://www.php.net/manual/zh/class.exception.php

 

相关文章:

  • 2022-01-03
  • 2021-04-09
  • 2021-06-29
  • 2021-04-25
  • 2021-11-14
  • 2021-08-29
  • 2021-08-07
猜你喜欢
  • 2021-12-15
  • 2022-12-23
  • 2021-12-11
  • 2021-09-26
  • 2021-10-13
  • 2021-06-24
  • 2021-10-19
相关资源
相似解决方案