2011-05-03 74 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. 
... 
相关问题