Ed *_*yer 5 error-handling perl die
这是"如何在Perl库中绕过'die'调用我无法修改?"的后续内容..
我有一个子程序,它调用一个库 - 崩溃 - 有时很多次.而不是使用eval {}在这个子例程中调用每个调用,我只是让它死掉,并在调用我的子例程的级别上使用eval {}:
my $status=eval{function($param);};
unless($status){print $@; next;}; # print error and go to
# next file if function() fails
Run Code Online (Sandbox Code Playgroud)
但是,我可以在函数()中捕获错误条件.在子例程和调用例程中设计错误捕获的最恰当/优雅的方法是什么,以便我获取捕获和未捕获错误的正确行为?
块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 $@";
};
Run Code Online (Sandbox Code Playgroud)