【问题标题】:How do I handle both caught and uncaught errors in a Perl subroutine?如何在 Perl 子例程中处理已捕获和未捕获的错误?
【发布时间】:2010-10-15 13:58:55
【问题描述】:

这是"How can I get around a ‘die’ call in a Perl library I can’t modify?" 的后续。

我有一个子例程,它多次调用 Library-Which-Crashes-Sometimes。我没有用 eval{} 来处理这个子例程中的每个调用,而是让它死掉,并在调用我的子例程的级别上使用 eval{}:

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

但是,我可以并且确实可以在 function() 中捕获一些错误情况。在子例程和调用例程中设计错误捕获的最合适/优雅的方法是什么,以便我获得捕获和未捕获错误的正确行为?

【问题讨论】:

    标签: perl error-handling die


    【解决方案1】:

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

    【讨论】:

    • 你的括号看起来很漂亮! +1
    • 好吧,我今天早上确实擦亮了它们。
    【解决方案2】:

    我不完全确定您想要做什么,但我认为您可以使用处理程序来完成。

    $SIG{__DIE__} = sub { print $@ } ;
    
    eval{ function($param); 1 } or next;
    

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多