PHP学习笔记15——错误与异常

 1 <?php
 2     //1. 开启错误报告
 3         /* 配置文件中display_errors和error_reporting用于配置错误报告级别
 4          * 首先要设置display_errors为On,也可以在脚本中ini_set('display_errors', 1)
 5          * 之后设置错误报告级别error_reporting(E_ERROR),参数是错误的报告级别
 6          */
 7 
 8     //2. 自定义错误
 9         /* trigger_error(str,E_ERROR)        可以代替die,自定义一个错误
10          * set_error_handle(error_handle)    设置处理错误的回调函数
11          */
12     error_reporting(0);    //关闭错误警告
13     set_error_handler('error_handle');    //设置处理错误的函数
14     echo $aaaa;    //notice,未定义变量
15     echo 3/0;    //warning,除0
16     trigger_error("a error", E_USER_ERROR);    //error,自定义错误
17     function error_handle($error_level, $error_message, $file, $line) {
18         $EXIT = false;
19         switch($error_level) {
20             case E_NOTICE:
21             case E_USER_NOTICE:
22                 $error_type = 'NOTICE';
23                 break;
24             case E_WARNING:
25             case E_USER_WARNING:
26                 $error_type = 'WARNING';
27                 break;
28             case E_ERROR:
29             case E_USER_ERROR:
30                 $error_type = 'FATAL ERROR';break;
31                 $EXIT = true;
32                 break;
33             default:
34                 $error_type = 'UNKNOWN';
35                 $EXIT = true;
36                 break;
37         }
38         printf("<font color='#FF0000'><b>%s</b></font>: %s in <b>%s</b> on line <b>%d</b><br>\n",
39         $error_type, $error_message, $file, $line);
40         
41         if ($EXIT){
42             //跳转到错误窗口
43             //echo '<script>location="err.html";</script>'
44         }
45     }
46     
47     //3. 写错误日志
48         /* 使用指定文件记录错误报告日志,应作如下配置
49          *     error_reporting = E_ALL
50          *     display_errors = Off
51          *     log_errors = On                            
52          *     log_errors_max_len = 1024                ;每个日志项最大长度
53          *     error_log = /usr/local/error.log        ;位置
54          * 可以使用error_log来送出用户自定义的信息  error_log(message,[type,des,extra_headers])
55          *     error("aa",0)                    //写入到操作系统日志中
56          *     error("aa",1,aa@aa.com)            //写入到管理员邮箱中
57          *     error("aa",2,"localhost:5050")    //发送到5050端口的服务器中
58          *     error("aa",3,/usr/a.log)        //发送到指定文件中
59          */
60 
61     //4. 异常处理
62         /* try{..}catch{..}
63          * 和java中代码结构一样,但在php中必须要手动抛出异常
64          * 可以继承Exception类实现自己的异常类
65          */
66     try {
67         echo "Before throw<br>";
68         throw new Exception("throw me");
69         echo "After throw<br>";
70     } catch (Exception $e) {
71         echo "Caught Exception: {$e->getMessage()} <br>";
72     }
73     
74 ?>

执行结果

posted @ 2013-08-22 16:32  Burn_E  阅读(278)  评论(0编辑  收藏  举报