在 Perl 中处理异常的最佳方法是什么? [英] What is the best way to handle exceptions in Perl?

查看:35
本文介绍了在 Perl 中处理异常的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Exception.pm 和 Error.pm 在 Perl 社区中似乎没有被广泛使用.是不是因为 eval 用于异常处理的占用空间很大?

I've noticed that Exception.pm and Error.pm don't seem to be extensively used in the Perl community. Is that due to the large footprint of eval for exception handling?

此外,Perl 程序似乎对一般的异常处理有更宽松的政策.这有什么令人信服的理由吗?

Also Perl programs appear to have a much more lenient policy regarding exception handling in general. Is there a compelling reason for this?

无论如何,Perl 中处理异常的最佳方法是什么?

In any event what would be the best method for exception handling in Perl?

推荐答案

Perl 社区的共识似乎是 Try::Tiny 是进行异常处理的首选方式.宽松政策"您所指的可能是由于以下原因的组合:

The consensus of the Perl community seems to be that Try::Tiny is the preferred way of doing exception handling. The "lenient policy" you refer to is probably due to a combination of:

  • Perl 不是完全面向对象的语言.(例如,与 Java 相比,其中您无法避免处理异常.)
  • 许多 Perl 开发人员的背景.(像 C1 和 shell 这样的语言没有异常机制.)
  • 人们倾向于使用 Perl 执行的任务类型.(用于文本编辑和在不需要异常处理的情况下生成报告.)
  • Perl 没有(好的)内置异常机制.
  • Perl not being a fully object-oriented language. (e.g. in contrast to Java where you can't avoid dealing with exceptions.)
  • The background of many Perl developers. (Languages like C1 and shell don't have exception mechanisms.)
  • The kind of tasks people tend to use Perl for. (Small scripts for text munging and report generation where exception handling isn't needed.)
  • Perl not having a (good) built-in exception mechanism.

注意最后一项意味着你会看到很多这样的代码:

Note that the last item means that you'll see a lot of code like this:

eval { something() };
if ($@) {
    warn "Oh no! [$@]
";
}

即使不使用 try/catch 语法,这也是异常处理.但是,它很脆弱,并且会在大多数人没有想到的一些微妙的边缘情况下崩溃.编写 Try::Tiny 和 CPAN 上的其他异常处理模块是为了更容易做到正确.

That's exception handling even though it doesn't use try/catch syntax. It's fragile, though, and will break in a number of subtle edge cases that most people don't think about. Try::Tiny and the other exception handling modules on CPAN were written to make it easier to get right.

1.C 确实有 setjmp()longjmp(),它们可用于非常粗糙的异常处理形式.

1. C does have setjmp() and longjmp(), which can be used for a very crude form of exception handling.

这篇关于在 Perl 中处理异常的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆