Else

如果说 rescue 部分在发生错误时执行,而 ensure 无论是否发生错误都会执行,那么我们怎么才能只有在没有发生错误时指定执行某些代码?

这样做的方法是在 rescue 部分之后和 ensure 部分之前添加一个可选的 else 子句(如果有的话),如下所示:

  1. begin
  2. # code which may cause an exception
  3. rescue [Exception Type]
  4. else # optional section executes if no exception occurs
  5. ensure # optional exception always executes
  6. end

这是一个示例:

else.rb
  1. def doCalc( aNum )
  2. begin
  3. result = 100 / aNum.to_i
  4. rescue Exception => e # executes when there is an error
  5. result = 0
  6. msg = "Error: " + e
  7. else # executes when there is no error
  8. msg = "Result = #{result}"
  9. ensure # always executes
  10. msg = "You entered '#{aNum}'. " + msg
  11. end
  12. return msg
  13. end