處理多個異常

你可以在同一 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