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

查看:126
本文介绍了在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开发人员的背景。 (像C 1 和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! [$@]\n";
}

即使不使用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天全站免登陆