[英]How do I handle both caught and uncaught errors in a Perl subroutine?
This is a followup to "How can I get around a 'die' call in a Perl library I can't modify?" 这是“如何在Perl库中绕过'die'调用我无法修改?”的后续内容。 .
。
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:
而不是使用eval {}在这个子例程中调用每个调用,我只是让它死掉,并在调用我的子例程的级别上使用eval {}:
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?
在子例程和调用例程中设计错误捕获的最恰当/优雅的方法是什么,以便我获取捕获和未捕获错误的正确行为?
Block eval can be nested: 块eval可以嵌套:
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 $@";
};
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.