php Exception 详解

Exception 类是php所有异常的基类。这个类包含如下方法:

__construct — 异常构造函数
getMessage — 获取异常消息内容
getPrevious — 返回异常链中的前一个异常
getCode — 获取异常代码
getFile — 获取发生异常的程序文件名称
getLine — 获取发生异常的代码在文件中的行号
getTrace — 获取异常追踪信息
getTraceAsString — 获取字符串类型的异常追踪信息

以上方法的简介直接从PHP官网抄来的。

下面写个例子:

01function handleException(Exception $e)
02{
03    do{
04        echo "<b>错误信息</b>:" . $e->getMessage() . "</br>";
05        echo "<b>错误码</b>:" . $e->getCode() . "</br>";
06        echo "<b>错误文件</b>:" . $e->getFile() . "</br>";
07        echo "<b>错误行数</b>:" . $e->getLine() . "</br>";
08        echo "<b>错误行数</b>:" . $e->getPrevious() . "</br>";
09        echo "<b>异常追踪信息</b>:</br>";
10        echo "</pre>" . print_r($e->getTrace(), true) . "</pre></br>";
11        echo "***********</br>";
12    } while($e = $e->getPrevious());
13}
14 
15set_exception_handler("handleException");
16 
17class MyException extends Exception {}
18 
19function test($name) {
20    throw new Exception("Test exception", 1000);
21}
22 
23try{
24    test("codyi");
25} catch (Exception $ex) {
26    throw new MyException("My exception", 1001, $ex);
27}

输出结果:

01错误信息:My exception
02错误码:1001
03错误文件:/Users/liguosong/work/php/Testing/test.php
04错误行数:27
05错误行数: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}
06异常追踪信息:
07Array ( )
08***********
09错误信息:Test exception
10错误码:1000
11错误文件:/Users/liguosong/work/php/Testing/test.php
12错误行数:21
13错误行数:
14异常追踪信息:
15Array ( [0] => Array ( [file] => /Users/liguosong/work/php/Testing/test.php [line] => 25 [function] => test [args] => Array ( [0] => codyi ) ) )
16***********

 

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>