How do I handle both caught and uncaught errors in a Perl subroutine?
-
22-08-2019 - |
Question
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?
Solution
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 $@";
};
OTHER TIPS
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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow