码迷,mamicode.com
首页 > 其他好文 > 详细

错误和异常处理

时间:2015-10-21 22:42:18      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

一、错误处理

  1.常见的错误级别

// Notice
json_encode($arr);

// Warning
json_encode();

// Fatal error
jsonp_encode();

  2.设置php报告错误的级别

    错误级别查看可通过文档的 函数参考->错误处理->预定义常量 查看。

//只显示error类型的错误
error_reporting(E_ERROR);

// 报告所有错误,&(并且) ~(不包括)
error_reporting(E_ALL & ~E_NOTICE);

// 屏蔽所有错误
error_reporting(0);

  3.自定义错误处理

// 设置一个用户的函数(error_handler)来处理脚本中出现的错误
mixed  set_error_handler  ( callable  $error_handler  [, int $error_types  = E_ALL | E_STRICT  ] )

// error_handler( $errno ,  $errstr ,  $errfile ,  $errline )
function  myErrorHandler($errno, $errstr, $errfile, $errline){
    // code
}

  4.说明

    当使用set_error_handler处理错误的时候,php就不会把错误直接显示到页面上,而是优先调用我们的自定义函数,并且把参数传递给我们的自定义函数,这样我们就可以自己处理错误,完整代码如下:

set_error_handler("myErrorHandler");

/**
 * 当发生错误的时候调用这个函数,而不是报告到页面上
 * @param  string $errno   错误级别
 * @param  string $errstr  错误详情
 * @param  string $errfile 错误所在的文件
 * @param  int    $errline 错误所在的行
 */
function myErrorHandler($errno, $errstr, $errfile, $errline){
    $str = sprintf("发生了一个%s错误,具体错误是:%s,错误所在的文件名:%s,错误所在的行:%s \r\n",$errno, $errstr, $errfile, $errline);
    file_put_contents("./error.log", $str, FILE_APPEND);
}

// notice
json_encode($arr);
echo ‘111<br>‘;

// warning
json_encode();
echo "2222<br>";

二、异常处理

  1.在 PHP 代码中所产生的异常可被 throw 语句抛出并被 catch 语句捕获

try {
    echo "try block<br />";
    throw new Exception("test");
} catch (Exception $ex) {
    echo "catch block<br />";
}

// try block
// catch block

  2.设置一个用户定义的异常处理函数

// 设置一个用户定义的异常处理函数
set_exception_handler (‘exception_handler‘);

function  exception_handler ( $exception ) {
  echo  "异常信息是: "  ,  $exception -> getMessage (),  "\n" ;
}

throw new  Exception ( ‘页面错误‘ );
echo  "Not Executed\n" ;

  3.Exception类

    上面的 throw new  Exception ( ‘页面错误‘ ) 其实就相当于 $exception = new  Exception ( ‘页面错误‘ );  那么Exception中都有哪些内容呢?通过文档的 语言参考->预定义异常 可以看到

// Exception类定义了我们需要的一些属性和方法
Exception{
    /* 属性 */
    protected string $message;
    protected int $code;
    protected string $file;
    protected int $line;

    /* 方法 */
    public __construct  ([ string $message  = ""  [, int $code  = 0  [, Exception  $previous  = NULL    ]]] )
    final public string getMessage  ( void )
    final public Exception getPrevious  ( void )
    final public int getCode  ( void )
    final public string getFile  ( void )
    final public int getLine  ( void )
    final public array getTrace  ( void )
    final public string getTraceAsString  ( void )
    public string __toString  ( void )
    final private void __clone  ( void )
}

  所以我们可以通过$exception对象访问到很多的属性和方法

  4.Exception的子类

    通过文档的 语言参考->预定义异常 可以看到Exception 是所有异常的基类。 php还为我们扩展了很多的子类,参见 SPL异常处理,里面有很熟悉的 RuntimeException, 他其实就是继承了Exception类

技术分享

错误和异常处理

标签:

原文地址:http://www.cnblogs.com/wange/p/4896541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!