Ruby 使用 begin/rescue/ensure(Ruby 的 try/catch/finally 等价物)来处理错误。您 异常并 它们,使用 进行清理。Ruby 还允许方法级别的 rescue(没有显式 )以获得更简洁的代码。
raiserescueensurebeginbegin
result = risky_operation
rescue ArgumentError => e # rescue a SPECIFIC exception type
puts "Bad argument: #{e.message}"
rescue StandardError => e # broader catch (StandardError, not Exception)
puts "Error: #{e.message}"
retry if attempts < 3 # retry can re-run the begin block
else
puts "succeeded" # runs if NO exception
ensure
cleanup # ALWAYS runs (success or failure)
end
begin/rescue/ensure 是 Ruby 的 try/catch/finally。rescue 特定类型(rescue ArgumentError),使用 ensure 进行保证的清理,以及用于无错误情况的 else。retry 可以重新尝试块。
rescue => e # ✅ bare rescue catches StandardError (the right default)
rescue StandardError # ✅ explicit, same thing
rescue Exception # ❌ AVOID — catches EVERYTHING including system signals
# (Interrupt/Ctrl-C, SystemExit) — can break the program
重要: 一个简单的 rescue 捕获 StandardError(应用程序错误的正确默认值)。Rescuing Exception(根类)捕获所有内容,包括系统级信号如 Interrupt(Ctrl+C)和 SystemExit — 您通常不想捕获这些,因为它可能会阻止程序被中断或正确退出。这是 Ruby 中的常见错误。
raise ArgumentError, "Amount must be positive" # raise a built-in
raise "Something failed" # raises RuntimeError
# custom exception class
class InsufficientFundsError < StandardError # inherit from StandardError
def initialize(msg = "Not enough funds")
super
end
end
raise InsufficientFundsError
def process
do_work
rescue => e # rescue WITHOUT begin — applies to the whole method body
handle(e)
ensure
cleanup
end
正确的异常处理对于健壮的 Ruby 应用程序至关重要,理解 Ruby 的方法 — 包括其特定的习语和警告 — 很重要。
begin/rescue/ensure 结构(Ruby 的 try/catch/finally)、rescue 特定异常类型、使用 ensure 进行保证的清理,以及简洁的方法级别的 rescue(没有显式 begin)是基础日常知识。
特别重要且独特的 Ruby 要点是 StandardError 与 Exception 的区别:一个简单的 rescue(和正确的默认值)捕获 StandardError,但 rescuing Exception(层次结构的根)捕获所有内容 — 包括系统信号如 Interrupt(Ctrl+C)和 SystemExit — 您几乎从不想要,因为它可能会阻止程序被中断或正确退出,这是一个常见的有害错误。
理解您应该为应用程序错误 rescue StandardError(而不是 Exception)是重要的 Ruby 特定知识,可以防止真实的 bug。
了解结构、自定义异常类(继承自 StandardError)、retry、方法级别的 rescue 习语,尤其是 StandardError-not-Exception 的警告,对于编写健壮、正确的 Ruby 代码很重要,这些代码可以优雅地处理错误而不会破坏程序被中断的能力。
由于未处理的错误和 Exception-rescuing 错误都会导致真正的问题,掌握 Ruby 的异常处理 — 其结构、习语和关键的 StandardError 与 Exception 的区别 — 对于可靠的 Ruby 开发很重要,是频繁相关的知识,也是常见的面试主题。