检查是否引发错误

如果没有引发错误,你可以使用 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