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;
    }

  • 相关阅读:
    流畅 最好用的远程桌面推荐下?
    高性能远程桌面Splashtop 居家办公首选软件
    ShareConnect即将寿终正寝 Splashtop远程桌面会是最好的替代品
    详解Springboot中自定义SpringMVC配置
    Java中使用RSA算法加密
    Docker搭建MySQL主从复制
    SpringMVC中RequestContextHolder获取请求信息
    详解Redis持久化(RDB和AOF)
    Redis事务
    Springboot CORS跨域访问
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/7819882.html
Copyright © 2011-2022 走看看