如何在Perl子例程中处理捕获和未捕获的错误?

前端之家收集整理的这篇文章主要介绍了如何在Perl子例程中处理捕获和未捕获的错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是 “How can I get around a ‘die’ call in a Perl library I can’t modify?”的后续行动.

我有一个子程序,它调用一个库 – 崩溃 – 有时很多次.而不是使用eval {}在这个子例程中调用每个调用,我只是让它死掉,并在调用我的子例程的级别上使用eval {}:

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

但是,我可以在函数()中捕获错误条件.在子例程和调用例程中设计错误捕获的最恰当/优雅的方法是什么,以便我获取捕获和未捕获错误的正确行为?

解决方法

块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 $@";
};

猜你在找的Perl相关文章