在Ruby中失败与加薪:我们真的应该相信样式指南吗? [英] Fail vs. raise in Ruby : Should we really believe the style guide?

查看:102
本文介绍了在Ruby中失败与加薪:我们真的应该相信样式指南吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby提供了两种以编程方式引发异常的可能性: raise fail ,都为内核方法。根据文件,它们是绝对等价的。

Ruby offers two possibilities to cause an exception programmatically: raise and fail, both being Kernel methods. According to the documents, they are absolutely equivalent.

出于一种习惯,到目前为止我只使用了提高。现在,我发现了一些使用此处)。 > raise 捕获异常,失败处理并非要处理的严重错误。

Out of a habit, I used only raise so far. Now I found several recommendations (for example here), to use raise for exceptions to be caught, and fail for serious errors which are not meant to be handled.

但这真的有意义吗?当您编写一个类或模块,并在内部引起深处的问题(通过失败发出信号)时,正在审查代码的编程同事可能会很高兴地了解您的意图,但是使用我的代码的人很可能不会看我的代码,也无法知道异常是否是由 raise 或失败。因此,我谨慎使用提高失败不会影响他的决定,无论她是应该还是应该

But does it really make sense? When you are writing a class or module, and cause a problem deep inside, which you signal by fail, your programming colleagues who are reviewing the code, might happily understand your intentions, but the person who is using my code will most likely not look at my code and has no way of knowing, whether the exception was caused by a raise or by fail. Hence, my careful usage of raise or fail can't have any influence on his decision, whether she should or should not handle it.

有人可以看到我的论点中的缺陷吗?还是有其他条件,我可能想使用 fail 而不是 raise

Could someone see flaws in my arguments? Or are there other criteria, which might me want to use fail instead of raise?

推荐答案


使用'raise'捕获异常,而'fail'表示不应该处理的严重错误

use 'raise' for exceptions to be caught, and 'fail' for serious errors which are not meant to be handled

这不是官方样式指南或您提供的有关此问题的链接。

This is not what the official style guide or the link you provided say on the matter.

这里的意思是使用仅在救援块中提高。如果您想说失败,也可以使用 fail ,而当时使用 raise > throwthing (例外)。

What is meant here is use raise only in rescue blocks. Aka use fail when you want to say something is failing and use raise when rethrowing an exception.

至于重要吗 部分-严格来说,它不是最严格的一个遵循规则,但是对于任何约定,您都可以使用相同的参数。您应该按照以下顺序进行操作:

As for the "does it matter" part - it is not one of the most hardcore strictly followed rules, but you could make the same argument for any convention. You should follow in that order:


  1. 您的项目样式指南

  2. 您的公司样式指南

  3. 社区风格指南

理想情况下,这三个应该相同。

Ideally, the three should be the same.

更新:自此PR (2015年12月),惯例是始终使用提高

Update: As of this PR (December 2015), the convention is to always use raise.

这篇关于在Ruby中失败与加薪:我们真的应该相信样式指南吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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