开发者

How to use Perl Exceptions?

I have a Perl problem of the following kind:

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

Then I want to call a subroutine called CheckResult in Report.pm:

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

In another case I want to report if a particular command was executed, so I do something like this:

$Report->Chec开发者_高级运维kResult($ABC->Command(100,100), "Performing the command");

Now in Report.pm:

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

How do I use exception class and how to check if an exception is raised, and if so perform the task necessary?


Edit:

As of now, I have a module of the kind:

package MyExceptions;

use strict;
use warnings;

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

The other module is:

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;

The user would in turn script something like this:

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

Could someone help? Sorry about my ignorance, I haven't done exceptions at all.


It is no help if you throw an exception and the user runs code that does not catch it. The code for Exception::Class is quite simple:

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

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

Thus, it shows both the throwing code and the client code. The eval line is both "try" and "throw" syntax. The rest is catching. So in a sort of highlevel regurgitation of your specs it would look something like this:

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

Your client code would simply test--I recommend actually testing (and freezing) $@ first.

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" );
    }
}


in Report.pm :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜