8

如何检查导致脚本或eval块终止的异常类型?我需要知道错误的类型以及异常发生的位置。

4

1 回答 1

13

Perl 方式

惯用的 Perl 是我们要么忽略所有错误,要么捕获它们以记录或转发到其他地方:

eval { func() };  # ignore error

或者:

eval { func() };
if ($@) {
    carp "Inner function failed: $@";
    do_something_with($@);
}

或(使用Try::Tiny - 请参阅该页面以了解您可能希望在 Perl 的内置异常处理中使用它的原因):

try { func() }
catch {
     carp "Inner function failed: $_";
     do_something_with($_);
};

如果要检查异常类型,请使用正则表达式:

if ( $@ =~ /open file "(.*?)" for reading:/ ) {
    # ...
}

行和文件也在那个字符串中。

但这很讨厌,因为您必须知道确切的字符串。如果您真的想要良好的错误处理,请使用CPAN中的异常模块。

例外::类

$@ doesn't have to be a string, it can be an object. Exception::Class lets you declare and throw exception objects Java-style. You can pass arbitrary information (filename, etc.) with the error when you throw it and get that information out using object methods rather than regex parsing - including the file and line number of the exception.

If you're using a third party module that does not use Error::Exception, consider

$SIG{__DIE__} = sub { Exception::Class::Base->throw( error => join '', @_ ); };

This will transform all errors into Exception::Class objects.

Error::Exception sets up proper stringification for Exception::Class objects.

于 2010-03-01T10:21:11.140 回答