Else
如果说 rescue
部分在发生错误时执行,而 ensure
无论是否发生错误都会执行,那么我们怎么才能只有在没有发生错误时指定执行某些代码?
这样做的方法是在 rescue
部分之后和 ensure
部分之前添加一个可选的 else
子句(如果有的话),如下所示:
begin
# code which may cause an exception
rescue [Exception Type]
else # optional section executes if no exception occurs
ensure # optional exception always executes
end
这是一个示例:
else.rb
def doCalc( aNum )
begin
result = 100 / aNum.to_i
rescue Exception => e # executes when there is an error
result = 0
msg = "Error: " + e
else # executes when there is no error
msg = "Result = #{result}"
ensure # always executes
msg = "You entered '#{aNum}'. " + msg
end
return msg
end