• 【六】php 错误异常处理


    错误异常处理

    概念:代码在try代码块被调用执行,catch代码块捕获异常
    • 异常需要手动抛出
    • throw new Exception (‘message’,code)
    • throw将出发异常处理机制
    • 在try代码块之后,必须至少给出一个catch代码块 
    catch代码块结构:
      catch(typehint exception){//handle exception}

    Exception类

    构造函数:
    • new Exception("message",code)
    内置方法:
    • getCode():返回构造函数的code
    • getMessage():返回构造函数的message
    • getFile():返回产生异常的代码文件路径
    • getLine():返回产生异常的代码行号
    • getTrace():返回一个包含了产生异常的代码回退路径的数组
    • getTraceAsString():同getTrace,但信息会格式化成一个字符串
    • _toString():允许简单的显示一个Exception对象
    try{
        throw new Exception('a terrible error has occerred',42);
    }catch (Exception $e){
        echo "Exception".$e->getCode().":".$e->getMessage()."<br/>". "in".$e->getFile()."on line ".$e->getLine()."<br/>";
        echo $e;
    }
    用户自定义异常
    • 如果异常没有匹配的catch语句快,php将报告一个致命错误
    /**
    * 声明一个新的异常类,该类继承了Exception基类
    * 该类与Exception的差异在于重载了_toString()方法
    */
    class myException extends Exception{
        function __toString()
        {
           return "<table border='1'>
            <tr>
            <td>
            <strong>Exception".$this->getCode()."</strong>:".
    $this->getMessage()."<br/> in".$this->getFile(). "on line".$this->getLine().
            "</td></tr></table><br/>";
        }
    }
     
    try{
        throw new myException('error',22);
    }catch(myException $m){
        echo $m;
    }
    实际应用:
    try{
        if(!$a=fopen("hello.txt")) {
            throw new myException('error', 22);
        }
    }catch(myException $m){
        echo $m;
    }

  • 相关阅读:
    设计模式走一遍---观察者模式
    从0打卡leetcode之day 6--最长回文串
    回车与换行的故事
    线程安全(中)--彻底搞懂synchronized(从偏向锁到重量级锁)
    线程安全(上)--彻底搞懂volatile关键字
    从0打卡leetcode之day 5 ---两个排序数组的中位数
    聊一聊让我蒙蔽一晚上的各种常量池
    从零打卡leetcode之day 4--无重复最长字符串
    C4.5算法总结
    数据库游标使用
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/7819882.html
Copyright © 2020-2023  润新知