加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP中的异常知识

发布时间:2020-12-13 16:06:44 所属栏目:PHP教程 来源:网络整理
导读:一、绪 首先明确一点:异常和错误不是一回事。 一个异常(Exception)是一个程序执行过程中出现的一个例外或是一个事件,它中断了正常指令的运行,跳转到其他程序模块继续执行。 基本格式: try { // 进行异常检测的代码部分,比如 throw new Exception(‘手

一、绪

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读