2011-05-03 121 views
0

我有這樣如何捕獲異常但導致perl腳本繼續執行?

package MyExceptions; 

use strict; 
use warnings; 
use Exception::Class (
    'MyExceptions::TestException' => {    
       fields => [qw{message}], 
    } 
); 

use Moose::Util::TypeConstraints; 

class_type 'MyExceptions::TestException'; 

no Moose::Util::TypeConstraints; 
1; 
一個包例外

在溝通module..The例外得到投擲每當有作爲「ERROR」

if ($recv_data eq 'ERROR') 
    { 
     MyExceptions::TestException->throw(message => $data); 
    } 

    elsif ($recv_data eq 'YES') 
    {   
     return $data; 
    } 

劇本是這樣的

服務器響應
eval{ 
my $num = 0; 
my $flag = 0; 

    do 
    { 
     if($num>6) 
    { 
     $flag = 1; 
     print "NOT found"; 
    } 

     my $region = $obj->FindImage('SomeImage'); 
     my $x = $region->getX; 
     my $y = $region->getY; 
     if(($x > 0) && ($y>0)) 
     { 
      $flag = 1; 
      $obj->Command($x,$y); 


     } 
     else 
     { 
        $Obj->Command1('50','2','160','275','160','220'); 
     } 


$num++; 

} while($flag==0); 

$num = 0; 

return; 
}; 

    if (my $ex = [email protected]) { 

     my $e ; 

     if ($e = Exception::Class->caught('MyExceptions::ExecutionException')) 
    {  

     print $e->message; 
    } 

    } 

在這種情況下..如果找不到圖像,必須執行命令並再次查找圖像需要完成,但是,例外在服務器響應爲「錯誤」的情況下被拋出,因此腳本停止執行,命令執行和圖像搜索的下一次迭代不會發生。這怎麼可以接近和解決?

謝謝

回答

1

首先,你不能在evalreturn。所以它可能會觸及eval的終點並默默地死去。我之前遇到過這個問題,當時我正在學習的return。 :)

否則,據我所知,它會做你在問什麼。當你用eval包裝do {} while時,你的意思是你不希望如果有異常再次執行循環。如果你想再次嘗試找到圖像,那麼你需要弄清楚如何用類似的東西包裝:

# try 
eval { 
    my $region = $obj->FindImage('SomeImage'); 
    ... 
}; 
# catch 
if (my $ex = Exception::Class->caught('MyExceptions::ExecutionException')) { 
    # logic to decide whether or not to find another image 
    ... 
} 
# if we don't die/croak/"throw" in the if. 
...