Exception 类是php所有异常的基类。这个类包含如下方法:
__construct — 异常构造函数
getMessage — 获取异常消息内容
getPrevious — 返回异常链中的前一个异常
getCode — 获取异常代码
getFile — 获取发生异常的程序文件名称
getLine — 获取发生异常的代码在文件中的行号
getTrace — 获取异常追踪信息
getTraceAsString — 获取字符串类型的异常追踪信息
以上方法的简介直接从PHP官网抄来的。
下面写个例子:
function handleException(Exception $e) { do{ echo "<b>错误信息</b>:" . $e->getMessage() . "</br>"; echo "<b>错误码</b>:" . $e->getCode() . "</br>"; echo "<b>错误文件</b>:" . $e->getFile() . "</br>"; echo "<b>错误行数</b>:" . $e->getLine() . "</br>"; echo "<b>错误行数</b>:" . $e->getPrevious() . "</br>"; echo "<b>异常追踪信息</b>:</br>"; echo "</pre>" . print_r($e->getTrace(), true) . "</pre></br>"; echo "***********</br>"; } while($e = $e->getPrevious()); } set_exception_handler("handleException"); class MyException extends Exception {} function test($name) { throw new Exception("Test exception", 1000); } try{ test("codyi"); } catch (Exception $ex) { throw new MyException("My exception", 1001, $ex); }
输出结果:
错误信息:My exception 错误码:1001 错误文件:/Users/liguosong/work/php/Testing/test.php 错误行数:27 错误行数:exception 'Exception' with message 'Test exception' in /Users/liguosong/work/php/Testing/test.php:21 Stack trace: #0 /Users/liguosong/work/php/Testing/test.php(25): test('codyi') #1 {main} 异常追踪信息: Array ( ) *********** 错误信息:Test exception 错误码:1000 错误文件:/Users/liguosong/work/php/Testing/test.php 错误行数:21 错误行数: 异常追踪信息: Array ( [0] => Array ( [file] => /Users/liguosong/work/php/Testing/test.php [line] => 25 [function] => test [args] => Array ( [0] => codyi ) ) ) ***********