MarsMax
MarsMax

Reputation: 91

How to trap exceptions but cause the perl script to continue execution?

I have a package for exceptions like

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;

In Communicate module..The exception gets thrown whenever there is a server response as "ERROR"

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

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

The script is something like this

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 = $@ ) {

        my $e ;

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

         print $e->message;
    }

    }

In this case..if an image is not found, a command has to be executed and again a find image needs to be done, however, an exception is thrown in case the server responds as "Error", therefore the script stops execution and the command execution and the next iteration of image search does not happen. How can this be approached and resolved ?

Thank you,

Upvotes: 0

Views: 1023

Answers (1)

Axeman
Axeman

Reputation: 29854

First of all, you can't return in an eval. So it's probably hitting the end of the eval and die-ing silently. I've run into this before ... back when I was learning not to return from an eval. :)

Otherwise, as far as I can see, it would be doing what you are asking. When you wrap the do {} while with the eval, you're saying that you do not want the loop executed again if there is an exception. If you want another try at finding the image, then you need to figure out how to wrap just that with something like:

# 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.
...

Upvotes: 1

Related Questions