PHP中的异常知识

一、绪

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

一个异常(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

 

posted @ 2019-07-19 00:04  白開水  阅读(285)  评论(0编辑  收藏  举报