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

获得异常相关的更多信息

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

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

类方法接受的参数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值