5

这是“如何在无法修改的 Perl 库中绕过 'die' 调用?”的后续内容。.

我有一个调用 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() 中捕获了一些错误情况。在子例程和调用例程中设计错误捕获的最合适/优雅的方法是什么,以便我获得捕获和未捕获错误的正确行为?

4

2 回答 2

8

块 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 $@";
};
于 2009-03-25T22:08:30.180 回答
0

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

$SIG{__DIE__} = sub { print $@ } ;

eval{ function($param); 1 } or next;
于 2009-03-25T22:17:22.997 回答