【六】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 >
        <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;
}