Perl Try Catch处理模块之Try::Tiny
2014-09-24 15:45:21 阿炯

Try::Tiny - minimal try/catch with proper preservation of $@


这个模块提供了简便的'try/catch/finally'语句,旨在减少用eval块常见的错误,它通常与autodie模块配合使用。采用MIT协议授权。

$@:Perl解释器从eval语句返回的错误消息。

You can use Try::Tiny's try and catch to expect and handle exceptional conditions, avoiding quirks in Perl and common mistakes.

你可以使用Try::Tiny来捕获和处理异常情况,避免编程过程中常见的错误。这是一个轻量级的模块。
try{
 die "foo";
}catch{
 warn "caught error: $_"; # not $@
};

你还可以使用它就像一个独立的eval操作并忽略任何错误条件。显然,这是一个极端的用例不能轻易地使用。
try{
 die "foo";
};

If the try block dies, it returns the value of the last statement executed in the catch block, if there is one. Otherwise, it returns undef in scalar context or the empty list in list context.

如果try块'die',如果有的话它将返回的值在catch块最后一条语句的执行;否则,它在标量上下文或空的列表在上下文将返回undef。

The following examples all assign "bar" to $x:
use v5.10;
use Try::Tiny;
use Data::Dumper;

my $x;
#$x = try { die "foo" } catch { "bar" };
#try { die "foo" } catch { $x="bar" };
#try { die "foo" } || { $x="bar" };
#(try { die "foo" }) // { $x="bar" };
#try { die 'foo' } finally { $x = 'bar' };
#try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };
#$x = eval { die "foo" } || "bar";

say Dumper($x);

finally blocks are always executed making them suitable for cleanup code which cannot be handled using local. You can add as many finally blocks to a given try block as you like.

'finally'总是使他们适合清理执行代码块,不能用于本地处理,你可以添加尽可能多处理代码给try块。

调用方法

try     { ... }
catch   { ... }
finally { ... };

try     { ... }
finally { ... };


try     { ... }
finally { ... }
catch   { ... };

You must always do your own error handling in the finally block. Try::Tiny will not do anything about handling possible errors coming from code located in these blocks.
try {
 die_sometimes();
} catch {
 # ...code run in case of error
} finally {
 if (@_) {
  print "The try block died with: @_\n";
 } else {
  print "The try block ran without error.\n";
 }
};

在'eval'块中处理出错
When you run an eval block and it succeeds, $@ will be cleared, potentially clobbering an error that is currently being caught.

This causes action at a distance, clearing previous errors your caller may have not yet handled.$@ must be properly localized before invoking eval in order to avoid this issue.

For this reason try will actually set $@ to its previous value (the one available before entering the try block) in the beginning of the eval block.


最新版本:0.2


项目主页:https://metacpan.org/release/Try-Tiny