|
参考文献:http://www.w3school.com.cn/php/php_exception.asp
我经常遇到一个报错:Uncaught exception 'Exception' ;
其实这就是后台代码 未捕获异常的错误报告。
当异常被抛出时,后面的代码不会执行,PHP会寻找相应的catch 代码块,如果未捕获或者未使用set_exception_hander() 作相应的处理的话,那么会发生一个严重错误。就是上面 红色的大字! 你还别说 我总算是知道为啥 我扒 易企秀总是失败了。
语法: - try{
- //可能出现错误或者异常的代码
- //catch 表示捕获 Exception是PHP已定义号的异常类
- }catch(Exception $e){
- //对异常处理的方法 1. 自己处理 ; 2.不处理将其抛出 ;
- }
复制代码 解读:
Try ---- 使用异常的函数应该位于 try内
Throw ---- 这里规定如何处罚异常(无异常无反应,必须对应至少一个 catch)
Catch ----异常代码捕获模块
举例- <?php
- //创建可抛出一个异常的函数
- function checkNum($number)
- {
- if($number>1)
- {
- throw new Exception("Value must be 1 or below");
- }
- return true;
- }
- //在 "try" 代码块中触发异常
- try
- {
- checkNum(2);
- //If the exception is thrown, this text will not be shown
- echo 'If you see this, the number is 1 or below }
- //捕获异常
- catch(Exception $e)
- {
- echo 'Message: ' .$e->getMessage();
- }
- ?>
复制代码 解析上面复制粘贴w3c的代码:
catch 代码块接收到异常,并创建一个包含异常信息的对象 ($e);通过这个exception对象 调用 $e->getMessage() ,输出来自该异常的错误信息;
Exception 具有几个基本属性与方法,其中包括了:
message---- 异常消息内容
code----异常代码
file----抛出异常的文件名
line----抛出异常在该文件的行数
方法有
getTrace---- 获取异常追踪信息
getTraceString----获取异常追踪信息的字符串
getMessage----获取出错信息
getLine---- 异常行号
getFile---- 所在文件
将异常记录到日志中: file_put_contents(error log;$msg)
将异常展示到网页中: echo n12br($msg)
|
|