处理多个异常

你可以在同一 rescue 声明中处理多个错误:

begin
  # an execution that may fail
rescue FirstError, SecondError => e
  # do something if a FirstError or SecondError occurs
end

你还可以添加多个 rescue 声明:

begin
  # an execution that may fail
rescue FirstError => e
  # do something if a FirstError occurs
rescue SecondError => e
  # do something if a SecondError occurs
rescue => e
  # do something if a StandardError occurs
end

rescue 块的顺序是相关的:第一个匹配是执行的匹配。因此,如果你将 StandardError 作为第一个条件并且所有异常都继承自 StandardError,则其他 rescue 语句将永远不会被执行。

begin
  # an execution that may fail
rescue => e
  # this will swallow all the errors
rescue FirstError => e
  # do something if a FirstError occurs
rescue SecondError => e
  # do something if a SecondError occurs
end

有些块具有隐式异常处理,如 defclassmodule。这些块允许你跳过 begin 语句。

def foo
    ...
rescue CustomError
    ...
ensure
    ...
end