“raise”foo“”和“raise Exception.new(”foo“)”之间有什么区别? [英] What is the difference between `raise "foo"` and `raise Exception.new("foo")`?

查看:130
本文介绍了“raise”foo“”和“raise Exception.new(”foo“)”之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 提高foo
有什么区别 - 技术,哲学,概念或其他

 提高Exception.new(foo)

解决方案

技术上,第一个引发一个RuntimeError,消息设置为foo,第二个引发异常消息设置为foo



实际上,您希望在何时使用前者和当你想使用后者。



简单地说,你可能想要一个 RuntimeError 而不是一个异常。没有参数的救援块将捕获 RuntimeErrors ,但不会捕获异常 s。所以如果你在你的代码中提出一个 Exception ,那么这段代码就不会出现:

  begin 
rescue
end

为了抓住例外您将不得不这样做:

  begin 
rescue例外
end

这意味着在某种意义上说,异常是一个比 RuntimeError 更差的错误,因为你必须做更多的工作才能从中恢复。



所以你想要的取决于你的项目如何处理它的错误。例如,在我们的守护程序中,主循环有一个空白的救援,它将捕获 RuntimeErrors ,报告它们,然后继续。但是在一两种情况下,我们希望守护进程确实真的死于错误,在这种情况下,我们提出一个异常,直接通过我们的正常错误处理代码出来。



再次,如果您正在编写库代码,您可能需要一个 RuntimeError ,而不是一个异常,因为您的库的用户将会惊奇,如果它引发了一个空白的拯救块无法捕获的错误最后,我应该说, RuntimeError 是一个 StandardError 类的子类,实际的规则是尽管可以 raise 任何对象类型,空白 rescue 将默认只捕获从 StandardError 继承的任何东西。一切都必须具体。


What is the difference - technical, philosophical, conceptual, or otherwise - between

raise "foo"

and

raise Exception.new("foo")

?

解决方案

Technically, the first raises a RuntimeError with the message set to "foo", and the second raises an Exception with the message set to "foo".

Practically, there is a significant difference between when you would want to use the former and when you want to use the latter.

Simply put, you probably want a RuntimeError not an Exception. A rescue block without an argument will catch RuntimeErrors, but will NOT catch Exceptions. So if you raise an Exception in your code, this code will not catch it:

begin
rescue
end

In order to catch the Exception you will have to do this:

begin
rescue Exception
end

This means that in a sense, an Exception is a "worse" error than a RuntimeError, because you have to do more work to recover from it.

So which you want depends on how your project does its error handling. For instance, in our daemons, the main loop has a blank rescue which will catch RuntimeErrors, report them, and then continue. But in one or two circumstances, we want the daemon to really really die on an error, and in that case we raise an Exception, which goes straight through our "normal error handling code" and out.

And again, if you are writing library code, you probably want a RuntimeError, not an Exception, as users of your library will be surprised if it raises errors that a blank rescue block can't catch, and it will take them a moment to realize why.

Finally, I should say that the RuntimeError is a subclass of the StandardError class, and the actual rule is that although you can raise any type of object, the blank rescue will by default only catch anything that inherits from StandardError. Everything else has to be specific.

这篇关于“raise”foo“”和“raise Exception.new(”foo“)”之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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