OneSolitaryNoob
OneSolitaryNoob

Reputation: 5757

Ignoring errors in a Perl END block

How do I ignore a die() that occurs in a Perl END block?

As it is now I get

END failed--call queue aborted

And the error bubbles up the calling script.

Upvotes: 3

Views: 2132

Answers (3)

Paul Dixon
Paul Dixon

Reputation: 301085

Put your end block inside an eval { .... } - this should prevent the behaviour you describe.

#!/usr/bin/perl

print("hi there!\n");

END {
    eval{
        print("goodbye\n");
        die("this can't hurt....");
    };

    #detect if an error occurred in the eval
    if ( $@ ){
        print ("an error occurred: $@\n");
    }
}

Upvotes: 8

Arav
Arav

Reputation: 5247

Place your code inside eval block and if you want to retrieve the error message that die provides you can capture using if condition outside the block.

#!/usr/bin/perl
my $val=1;
eval
{
   print "Inside Eval\n";
   if($val == 1)
   {
     die "hello world\n";
   }
   print "End of Eval\n";
};
if ( $@ )
{
         print  "Error message - $@" . "\n";
}

Upvotes: 5

Borodin
Borodin

Reputation: 126762

Try::Tiny is an excellent wrapper for eval, allowing you to explicitly handle run-time exceptions.

Upvotes: 3

Related Questions