简体   繁体   English

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

[英]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.

相关问题 如何处理Perl中的子例程重新定义的错误 - How to handle subroutine redefined errors in Perl 如何在 perl 子程序签名中设置默认文件句柄? - How can I set a default file handle in a perl subroutine signature? 如何编写一个既可用作普通子程序又可用作类方法的Perl子程序? - How can I write a Perl subroutine that works both as a normal subroutine or a class method? 如何处理 Perl 中方法链中的错误? - How do I handle errors in methods chains in Perl? 如何将文件句柄传递给Perl子程序? - How to pass and read a File handle to a Perl subroutine? 在Perl中,如果可能,如何将通用菱形(&lt;&gt;)文件句柄传递给子例程? - In Perl, if possible, how do I pass a generic diamond (<>) filehandle to a subroutine? 如何将Perl数组作为标量传递到子例程中? - How do I pass a Perl array as a scalar into a subroutine? 在调用Perl子例程时如何传递匿名子例程? - How do I pass an anonymous subroutines when calling a Perl subroutine? 如何在Perl中迭代/取消引用子例程引用数组? - How do I iterate over/dereference an array of subroutine refs in Perl? 如何从Perl / TK中的子例程获取调用者窗口小部件? - How do I get the caller widget from a subroutine in Perl/TK?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM