Ruby异常 - 为什么“其他”? [英] Ruby Exceptions -- Why "else"?
问题描述
我正在尝试了解Ruby中的异常,但我有点困惑。我使用的教程说,如果发生不符合救援声明所指定的任何异常的异常,您可以使用else来捕捉:
I'm trying to understand exceptions in Ruby but I'm a little confused. The tutorial I'm using says that if an exception occurs that does not match any of the exceptions identified by the rescue statements, you can use an "else" to catch it:
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end
然而,我稍后在教程救援中也看到没有指定例外:
However, I also saw later in the tutorial "rescue" being used without an exception specified:
begin
file = open("/unexistant_file")
if file
puts "File opened successfully"
end
rescue
file = STDIN
end
print file, "==", STDIN, "\n"
如果可以这样做那么我是否需要使用其他的东西?或者我可以这样使用一般的救援?
If you can do this, then do I ever need to use else? Or can I just use a generic rescue at the end like this?
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
rescue
# Other exceptions
ensure
# Always will be executed
end
推荐答案
else
是在块完成时没有抛出异常的情况。无论块是否成功完成,都会运行确保
。示例:
The else
is for when the block completes without an exception thrown. The ensure
is run whether the block completes successfully or not. Example:
begin
puts "Hello, world!"
rescue
puts "rescue"
else
puts "else"
ensure
puts "ensure"
end
这将打印 Hello,world!
,然后 else
,然后确保
。
This will print Hello, world!
, then else
, then ensure
.
这篇关于Ruby异常 - 为什么“其他”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!