PHP5的异常处理机制[13]--获得异常相关的更多信息

王朝php·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

获得异常相关的更多信息

以下是用来格式化输出异常信息的代码:

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

类方法接受的参数

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航