How do I handle both caught and uncaught errors in a Perl subroutine?
Asked Answered
E

2

5

This is a followup to "How can I get around a ‘die’ call in a Perl library I can’t modify?".

I have a subroutine that calls a Library-Which-Crashes-Sometimes many times. Rather than couch each call within this subroutine with an eval{}, I just allow it to die, and use an eval{} on the level that calls my subroutine:

my $status=eval{function($param);};
unless($status){print $@; next;}; # print error and go to
                                  # next file if function() fails

However, there are error conditions that I can and do catch in function(). What is the most proper/elegant way to design the error-catching in the subroutine and the calling routine so that I get the correct behavior for both caught and uncaught errors?

Equitable answered 25/3, 2009 at 21:57 Comment(0)
O
8

Block eval can be nested:

sub function {
    eval {
        die "error that can be handled\n";
        1;
    } or do {
        #propagate the error if it isn't the one we expect
        die $@ unless $@ eq "error that can be handled\n"; 
        #handle the error
    };
    die "uncaught error";
}

eval { function(); 1 } or do {
    warn "caught error $@";
};
Overpower answered 25/3, 2009 at 22:8 Comment(2)
Your brackets look spiffy! +1Pentheam
Well, I did polish them this morning.Overpower
C
0

I'm not completely sure what you want to do, but I think you can do it with a handler.

$SIG{__DIE__} = sub { print $@ } ;

eval{ function($param); 1 } or next;
Charmer answered 25/3, 2009 at 22:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.