如何使用Perl Exceptions?

时间:2011-04-20 09:06:23

标签: perl exception

我遇到以下类型的Perl问题:

$object1 = $ABC->Find('test1');

然后我想在CheckResult中调用一个名为Report.pm的子程序:

$Report->CheckResult($object, "Finding the value");

在另一种情况下,我想报告是否执行了特定命令,所以我做了类似这样的事情:

$Report->CheckResult($ABC->Command(100,100), "Performing the command");

现在在Report.pm

sub CheckResult {
    my ($result, $information) = @_;
    # Now, I need something like this
    if ($result->isa('MyException')) {
        # Some code to create the report
    }
}

如何使用异常类以及如何检查是否引发异常,如果是,则执行必要的任务?


编辑:

截至目前,我有一个类似的模块:

package MyExceptions;

use strict;
use warnings;

use Exception::Class (
    'MyExceptions',
    'MyExceptions::RegionNotFound'     => {isa => 'MyExceptions'},
    'MyExceptions::CommandNotExecuted' => {isa => 'MyExceptions'}
);

另一个模块是:

package ReportGenerator;

use strict;
use warnings;

sub CheckResult {
    my ($result, $info) = @_;

    # Here is want to check of $result and throw an exception of the kind
    # MyExceptions::RegionNotFound->throw(error => 'bad number');
    # I'm not sure how to do this
}
1;

用户反过来会编写如下内容:

$Report->CheckResult($ABC->Command(100,100), "Tapping Home");

有人可以帮忙吗?对于我的无知感到抱歉,我根本没有例外。

2 个答案:

答案 0 :(得分:3)

如果抛出异常并且用户运行的代码没有捕获它,则无济于事。 Exception::Class的代码非常简单:

# try
eval { MyException->throw( error => 'I feel funny.' ) };

# catch
if ( $e = Exception::Class->caught('MyException') ) {
    ...

因此,它显示了抛出代码和客户端代码。 eval行是“try”和“throw”语法。剩下的就是捕捉。因此,在您的规格的某种高级反流中,它看起来像这样:

if ( !Object->find_region( $result )) { # for OO goodness
    MyExceptions::RegionNotFound->throw( error => 'bad number' );
}

您的客户端代码只是测试 - 我建议首先实际测试(和冻结$@

eval { 
    $Report->CheckResult($ABC->Command(100,100), "Tapping Home");
};
if ( my $ex = $@ ) { # always freeze $@ on first check
    my $e;
    if ( $e = Exception::Class->caught('MyExceptions::RegionNotFound')) { 
        warn( $e->error, "\n", $e->trace->as_string, "\n" );
    }
}

答案 1 :(得分:-2)

报告中的

sub CheckResult {
    try {
        $Report->CheckResult($object,”Finding the value”);
    } catch MyException with {
       # Exception handling code here
    };
}