Exception 类是php所有异常的基类。这个类包含如下方法:
__construct — 异常构造函数
getMessage — 获取异常消息内容
getPrevious — 返回异常链中的前一个异常
getCode — 获取异常代码
getFile — 获取发生异常的程序文件名称
getLine — 获取发生异常的代码在文件中的行号
getTrace — 获取异常追踪信息
getTraceAsString — 获取字符串类型的异常追踪信息
以上方法的简介直接从PHP官网抄来的。
下面写个例子:
01 | function handleException(Exception $e ) |
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()); |
15 | set_exception_handler( "handleException" ); |
17 | class MyException extends Exception {} |
20 | throw new Exception( "Test exception" , 1000); |
25 | } catch (Exception $ex ) { |
26 | throw new MyException( "My exception" , 1001, $ex ); |
输出结果:
03 | 错误文件:/Users/liguosong/work/php/Testing/test.php |
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} |
11 | 错误文件:/Users/liguosong/work/php/Testing/test.php |
15 | Array ( [0] => Array ( [file] => /Users/liguosong/work/php/Testing/test.php [line] => 25 [ function ] => test [args] => Array ( [0] => codyi ) ) ) |