2011-04-20 62 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