zoukankan      html  css  js  c++  java
  • 【六】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;
    }

  • 相关阅读:
    一个人的旅行 dij(),评测的时候有点惨
    CodeFroce Round 340 div2 E XOR and Favorite Number【莫队算法】
    [HihoCoder-1185] 连通性·三 【tarjan+缩点】
    2017百度之星初赛(A)1001,1005,1006解题报告
    HDU 5961&AOJ 821 传递
    pair
    优先队列 priority_queue
    ccf 201903-5
    memset 和 fill 的区别
    ccf 20190302
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/7819882.html
Copyright © 2011-2022 走看看