处理异常

使用 begin/rescue 块来捕获(救援)异常并处理它:

begin
  # an execution that may fail
rescue
  # something to execute in case of failure
end

rescue 子句类似于 C#或 Java 等大括号语言中的 catch 块。

像这样的裸露的 rescue 救了 StandardError

注意:注意避免捕捉 Exception 而不是默认的 StandardErrorException 类包括 SystemExitNoMemoryError 以及你通常不想捕获的其他严重异常。始终考虑捕捉 StandardError(默认值)。

你还可以指定应该获救的异常类:

begin
  # an excecution that may fail
rescue CustomError
  # something to execute in case of CustomError
  # or descendant
end

这个救援条款不会发现任何不是非法的例外 12。

你还可以将异常存储在特定变量中:

begin
  # an excecution that may fail
rescue CustomError => error
  # error contains the exception
  puts error.message # provide human-readable details about what went wrong.
  puts error.backtrace.inspect # return an array of strings that represent the call stack
end

如果你未能处理异常,你可以随时在救援区中提起异常。

begin
   #here goes your code
rescue => e
    #failed to handle 
    raise e
end

如果你想重试你的 begin 块,请致电 retry

begin
   #here goes your code
rescue StandardError => e
   #for some reason you want to retry you code
   retry
end

如果在每次重试中都捕获异常,则可能会陷入循环。要避免这种情况,请将 retry_count 限制为一定次数。

retry_count = 0
begin
      # an excecution that may fail
rescue
    if retry_count < 5
        retry_count = retry_count + 1
        retry
    else
        #retry limit exceeds, do something else
    end

你还可以提供 else 街区或 ensure 街区。当 begin 块完成而没有抛出异常时,将执行 else 块。始终会执行 ensure 块。ensure 块类似于使用 C#或 Java 等大括号语言的 finally 块。

begin
  # an execution that may fail
rescue
  # something to execute in case of failure
else
  # something to execute in case of success
ensure
  # something to always execute
end

如果你在 defmoduleclass 块中,则不需要使用 begin 语句。

def foo
    ...
rescue
    ...
end