檢查是否引發錯誤

如果沒有引發錯誤,你可以使用 else 子句來執行程式碼。

def divide(x, y)
  begin
    z = x/y
  rescue ZeroDivisionError
    puts "Don't divide by zero!"
  rescue TypeError
    puts "Division only works on numbers!"
    return nil
  rescue => e
    puts "Don't do that (%s)" % [e.class]
    return nil
  else
    puts "This code will run if there is no error."
    return z
  end
end

如果存在將控制轉移到其中一個 rescue 子句的錯誤,則 else 子句不會執行:

> divide(10,0)
Don't divide by zero!
=> nil

但是如果沒有引發錯誤,則 else 子句執行:

> divide(10,2)
This code will run if there is no error.
=> 5

請注意,*如果從 begin 子句返回,*則不會執行 else 子句

def divide(x, y)
  begin
    z = x/y
    return z                 # Will keep the else clause from running!
  rescue ZeroDivisionError
    puts "Don't divide by zero!"
  else
    puts "This code will run if there is no error."
    return z
  end
end

> divide(10,2)
=> 5