【问题标题】:Why doesn't Perl's eval catch problems from Test::Cmd::Common->unlink?为什么 Perl 的 eval 不能从 Test::Cmd::Common->unlink 捕获问题?
【发布时间】:2010-01-13 02:22:38
【问题描述】:

我有以下 perl 代码:

use strict;
use warnings;
use Test::Cmd::Common;

my $path = "/something/not/available";
my $test = Test::Cmd::Common->new(string => 'File system operations');

eval{
        $test->unlink("$path");
};
ok(!$@, "file unlike");

print "done.\n";

$test->unlink() 行将失败并抛出异常。但问题是:eval 没有处理该异常,代码执行被中断。

输出:

$ perl test.pl 
could not unlink files (/something/not/available): No such file or directory
NO RESULT for test at line 561 of /home/y/lib/perl5/site_perl/5.8/Test/Cmd/Common.pm (Test::Cmd::Common::unlink)
    from line 9 of test.pl.

eval 在这里做得对吗?还是我误会了什么?

F。

【问题讨论】:

    标签: perl eval


    【解决方案1】:

    来自 Test::Cmd::Common 的文档:“删除指定的文件。如果由于任何原因无法删除任何文件,则退出 NO RESULT。”。通过查看源代码,Test::Cmd::Common 调用了 Test::Cmd->no_result,确实如此

    exit (2);
    

    "exit" 不能被 eval 捕获,所以这是预期的行为。

    【讨论】:

    • 未经测试,但*Test::Cmd::no_result = sub { die 'No result' } 怎么样?
    【解决方案2】:

    这有点正交,但如果你想测试一个操作是“成功”还是死亡,请使用Test::Exception

    use strict;
    use warnings;
    use Test::More tests => 2;
    use Test::Exception;
    
    note 'File system operations';
    dies_ok
        { some_operation_which_may_die(); }
        'operation died';
    
    throws_ok
        { some_operation_which_may_die(); }
        /String we expect to see on death/,
        'operation died with expected message';
    

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多