在 Perl 5.14 或更高版本中,是否仍建议 Try::Tiny 用于异常处理? [英] Is Try::Tiny still recommended for exception handling in Perl 5.14 or later?
问题描述
Perl 社区的共识似乎是 Try::Tiny
是处理异常的首选方式.
The consensus of the Perl community seems to be that Try::Tiny
is the preferred way to handle exceptions.
Perl 5.14(这是我使用的版本)似乎解决了问题 eval
解决了 Try::Tiny
的问题.Try::Tiny
还会给我带来什么好处吗?
Perl 5.14 (which is the version I use) seems to solve the issues with eval
that Try::Tiny
addresses. Will Try::Tiny
still provide any benefits for me?
推荐答案
我的回答不受欢迎,但我认为 Perl 程序员不应该尝试使用我们在 Perl 中称为异常"的极其糟糕的概念.这些本质上是侧信道返回值.然而,仍然迷恋于异常的想法,即使使用全局变量来传递状态的所有复杂性,人们仍然试图让它工作.
My answer is unpopular, but I don't think Perl programmers should be trying to use the exceedingly poor notion of the thing we call "exceptions" in Perl. These are essentially a side channel return value. However, still being enamored with the idea of exceptions, even with all the complexities of using a global variable to pass around state, people keep trying to make it work.
然而,实际上,人们使用 die
来表示失败.有些人会说你可以用一个引用 die
并传回错误对象,但你不需要 die
.我们有对象,所以我们应该使用对象的所有功能:
Practically, however, people use die
to signal failure. Some will say that you can die
with a reference and pass back error objects, but you don't need die
for that. We have objects, so we should use all the power of objects:
sub some_sub {
...
return Result->new( error => 1, description => ... ) if $something_went_wrong;
return Result->new( error => 0, ... );
}
my $result = some_sub( ... );
if( $result->is_error ) { ... };
这不涉及全局变量、远距离动作、范围界定问题或需要特殊特殊功能.您创建一个小类 Result
或任何您想调用它的类来包装您的返回值,以便您拥有结构化数据而不是没有标识的单个值.不再想知道返回值意味着什么.那 undef
是真实值还是失败的迹象?返回值是否已定义或是否为真?你的对象可以告诉你这些事情.并且,您可以将相同的对象与 die
一起使用.如果您已经使用带有 die
的对象并将其用作返回值,那么几乎没有什么可以推荐您为容忍 $@
而必须做的所有额外事情.
That doesn't involve global variables, action at a distance, scoping headaches, or require special specials. You create a tiny class Result
, or whatever you want to call it, to wrap your return values so you have structured data instead of single values with no identity. There's no more wondering what a return value means. Is that undef
a real value or an indication of failure? Is the return value good if it's defined or if it's true? Your object can tell you these things. And, you can use the same object with die
. If you're already using the object with die
and using it as the return value, there's very little to recommend all the extra stuff you have to do to tolerate $@
.
然而,我知道你无法帮助别人做什么,所以你仍然必须假装 Perl 有例外.
However, I know that you can't help what other people do, so you still have to pretend Perl has exceptions.
这篇关于在 Perl 5.14 或更高版本中,是否仍建议 Try::Tiny 用于异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!