获得异常相关的更多信息
以下是用来格式化输出异常信息的代码:
index_php5_6.php
<?php
// PHP 5
class Front {
static function main () {
try {
$helper = new RequestHelper (array( cmd => 'realcommand' ));
$helper -> runCommand ();
} catch ( Exception $e ) {
print "<h1>" . get_class ( $e ). "</h1>\n" ;
print "<h2>{$e->getMessage()}
({$e->getCode()})</h2>\n\n" ;
print "file: {$e->getFile()}<br />\n" ;
print "line: {$e->getLine()}<br />\n" ;
print $e -> getTraceAsString ();
die;
}
}
}
Front :: main ();
?>
如果你的realcommand类无法被实例化(例如你将它的构造函数声明为private)并运行以上代码,你可以得到这样的输出:
ReflectionException
Access to non-public constructor of class realcommand (0)
file: c:\MyWEB\Apache\htdocs\php5exception\index_php5_4.php line: 31 #0 c:\MyWEB\Apache\htdocs\php5exception\index_php5_5.php(25): CommandManager->getCommandObject()
#1 c:\MyWEB\Apache\htdocs\php5exception\index_php5_6.php(10): RequestHelper->runCommand('realcommand')
#2 c:\MyWEB\Apache\htdocs\php5exception\index_php5_6.php(23): Front::main()
#3 {main}
你可以看到getFile()和getLine()分别返回发生异常的文件和行数。GetStackAsString()方法返回每一层导致异常发生的方法调用的细节。从#0一直到#4,我们可以清楚地看到异常传递的路线。
你也可以使用getTrace()方法来得到这些信息,getTrace()返回一个多维数组。第一个元素包含有异常发生的位置,第二个元素包含外部方法调用的细节,直到最高一层的调用。这个数组的每个元素本身也是一个数组,包含有以下几个键名(key):
key |
含义 |
file
|
产生异常的文件 |
line
|
产生异常的类方法所在行数 |
function
|
产生异常的函数/方法 |
class
|
调用的方法所在类 |
type
|
调用类型:'::' 表示调用静态类成员 '->' 表示实例化调用(先实例化生成对象再调用) |
args
|
类方法接受的参数 | 
|