Perl - messing try/catch with eval



如何从内部eval{}捕获异常?

#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny;
use Exception::Class ('T');
use Data::Dumper;
try {
eval {
T->throw("Oops");
};
} catch {
print Dumper $_;
};
}

我们得到的不是Exception::Class子模块,而是标量。更准确地说,我有很多带有require的遗留代码,而require似乎在内部使用了eval

您可以自动上转换异常,如下所示:

#!/usr/bin/perl
use strict;
use warnings;
use feature qw( say );
use Try::Tiny;
use Exception::Class ('T');
$SIG{__DIE__} = sub {
die($_[0]) if !defined($^S);
die($_[0]) if ref($_[0]) eq 'T';
T->throw($_[0]);
};
try {
die "foo";
} catch {
say ref($_) || "Not reference";
print $_;
};
try {
T->throw("foo");
} catch {
say ref($_) || "Not reference";
say $_;
};

如果在eval块内遇到异常,则块的返回值为undef(或列表上下文中的空列表(,并且Perl设置带有错误消息的特殊变量$@。错误消息通常是一个简单的标量,但它可以是引用或祝福引用——设置它的一种方法是使用die调用的参数,任何类型的值都可以传递给该函数。

try {
eval {
T->throw("Oops"); 1;
} or do {
warn "Exception caught in eval: $@";
# rethrow the exception outside eval
if (ref($@) eq 'T') {
$@->rethrow;
} else {
T->throw("Oops: $@");
}
}
} catch {
print Dumper $_;
};

最新更新