2011-04-20 56 views
2

我有以下类型的Perl的问题:如何使用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"); 

有人可以帮忙吗?对不起我的无知,我没有做过任何例外。

+0

我觉得异常::类将满足我的需要,可能会有人告诉我如何如果你的代码需要一个模块来使用它 – MarsMax 2011-04-20 09:34:25

回答

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

您的客户端代码只会测试 - 我建议实际测试(和冻结[email protected]第一。

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

谢谢Axeman ..你能解释这一行如果(!Object-> find_region($ result)) – MarsMax 2011-04-21 09:40:26

+1

@MarsMax:“检查$ result”的伪代码,只是用OO的术语'find_region'仅仅是因为你想要的异常抛出是'RegionNotFound'。因此,如果你*不*找到由'$ result'指示的RegionNotFound区域。 – Axeman 2011-04-21 12:18:35

+0

谢谢Axeman ..我终于得到了我想要的东西...看起来我无法处理可能由$ result..so提供的不同类型的对象,所以不需要从用户端脚本。 。看起来像'if(my $ ex = $ @){my $ e; if($ e = Exception :: Class-> caught('MyExceptions :: ExecutionException')){print $ e-> message; }}'然后抛出异常,像'MyExceptions :: ExecutionException-> throw(message => $ data)' – MarsMax 2011-04-21 13:02:27

-2

在Report.pm:

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

,请注明这一点。而且,没有任何解释的代码块并不是一个很好的答案。 – darch 2011-04-20 17:00:57