Ruby 异常与控制跳转
系统讲解 Ruby begin/rescue/else/ensure 异常处理结构、retry 重试机制、raise 四种抛出形式、catch/throw 非局部控制跳转以及 Exception 继承体系与自定义异常类。
学完这一章,你能够
- 系统讲解 Ruby begin/rescue/else/ensure 异常处理结构、retry 重试机制、raise 四种抛出形式、catch/throw 非局部控制跳转以及 Exception 继承体系与自定义异常类。
begin / rescue 基础异常处理机制
程序运行中打开不存在的文件、网络中断或参数非法都会触发异常;若不加以捕获,解释器将中止执行。Ruby 使用 `begin ... rescue ... end` 包裹受保护代码:一旦抛出异常,控制权转入匹配该异常类或其父类的 `rescue` 子句。注意不带类型参数的裸 `rescue` 默认只捕获 `StandardError` 及其子类(而非顶层 `Exception`,避免误拦截 `Interrupt` 或 `SystemExit`);在 `rescue` 内部可通过 `=> e` 绑定异常对象,或读取全局变量 `$!`(异常对象)与 `$@`(调用栈)。例如打开不存在文件失败后,可在 `rescue` 中回退赋值给 `STDIN`。
retry 重试与 raise 四种抛出形式
在 `rescue` 子句中调用 `retry` 可把控制流重新跳回 `begin` 块起始位置再次尝试执行。典型流程为:初次打开失败 → 进入 `rescue` 修正变量(如切换到备用文件名)→ `retry` 回到 `begin` → 成功打开并继续。但若修正后的条件依然失败且没有设置重试次数上限,`retry` 会陷入无限循环,因此工程中务必搭配计数器限制最大重试次数。
`raise` 用于主动抛出异常,支持四种常用写法:(1)无参 `raise` 重新抛出当前捕获的异常,若不在 `rescue` 上下文中则抛出默认 `RuntimeError`;(2)`raise "消息"` 创建带消息的 `RuntimeError`;(3)`raise ExceptionType, "消息"` 抛出指定异常类及描述;(4)在后方附加条件修饰符(如 `unless valid?`)。抛出后 `begin` 块剩余语句立即跳过,并可通过 `e.message` 与 `e.backtrace` 读取错误说明和堆栈轨迹。
ensure 清理与 else 无异常分支
`ensure` 子句放在所有 `rescue` 之后,无论受保护代码正常结束、被 `rescue` 捕获还是因未捕获异常向上传播,`ensure` 块中的收尾逻辑(如关闭文件句柄、释放锁或数据库连接)都必然执行。
`else` 子句位于最后一个 `rescue` 之后、`ensure` 之前,并且仅在 `begin` 主体完全没有抛出异常时才会执行(需要特别区分:它不是捕获未匹配异常的兜底分支,未匹配异常仍会继续向外冒泡)。在 `rescue` 块中,全局特殊变量 `$!` 始终引用当前抛出的异常实例。
catch / throw 正常控制跳转与 Exception 类层次
当并非发生错误,只是希望在满足某条件时直接跳出多层嵌套循环或递归调用时,应使用 `catch` 与 `throw` 而非异常机制。`catch(:quitRequested) do ... end` 定义带符号标签的拦截区,内部任意深度的 `throw :quitRequested`(还可附带第二个参数作为 `catch` 表达式的返回值)会立即终止内层执行并回到 `catch` 块末尾继续后续代码。
Ruby 所有异常类都派生自顶层 `Exception`,其下核心分支包括 `Interrupt`、`NoMemoryError`、`SignalException`、`ScriptError`、`StandardError`、`SystemExit` 以及解释器内部专用的 `fatal`。编写业务自定义异常类(如 `class FileSaveError < StandardError`)时,应继承自 `StandardError` 以便默认 `rescue` 正常捕获;并可在捕获底层 I/O 错误后通过 `raise FileSaveError.new($!)` 将原始原因封装后向上传递。
离线校验 Ruby begin/rescue/else/ensure、有界 retry、自定义异常与 catch/throw
"""Offline Ruby 3.x semantic verification lab for Chapter 30 (exceptions)."""
import json
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_begin_rescue_else_ensure_flow():
def run_block(should_raise: bool):
log = []
try:
log.append("begin_start")
if should_raise:
raise RuntimeError("A test exception.")
log.append("begin_end")
except RuntimeError as e:
log.append(f"rescue:{e}")
else:
log.append("else_no_error")
finally:
log.append("ensure_always")
return log
expected = {
"with_error": ["begin_start", "rescue:A test exception.", "ensure_always"],
"without_error": ["begin_start", "begin_end", "else_no_error", "ensure_always"],
}
actual = {
"with_error": run_block(True),
"without_error": run_block(False),
}
return {
"name": "begin_rescue_else_ensure_flow",
"summary": "核验 begin/rescue/else/ensure 执行分支:仅无异常时执行 else,无论是否异常均执行 ensure",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_retry_with_bounded_fallback():
available = {"existant_file": "ok-content"}
fname = "/unexistant_file"
attempts = 0
max_retries = 2
opened = None
while True:
attempts += 1
try:
if fname not in available:
raise FileNotFoundError(fname)
opened = available[fname]
break
except FileNotFoundError:
if attempts >= max_retries:
break
fname = "existant_file"
continue
expected = {"attempts": 2, "final_fname": "existant_file", "opened": "ok-content"}
actual = {"attempts": attempts, "final_fname": fname, "opened": opened}
return {
"name": "retry_with_bounded_fallback",
"summary": "核验 rescue 修正路径后通过 retry 重新执行 begin 块,并以重试上限防止死循环",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_raise_forms_and_custom_error():
class StandardErrorRb(Exception):
pass
class FileSaveError(StandardErrorRb):
def __init__(self, reason):
super().__init__(str(reason))
self.reason = reason
try:
try:
raise IOError("disk full")
except IOError as orig:
raise FileSaveError(orig) from orig
except FileSaveError as wrapped:
caught_type = type(wrapped).__name__
is_std = isinstance(wrapped, StandardErrorRb)
reason_msg = str(wrapped.reason)
expected = {
"caught_type": "FileSaveError",
"inherits_standard_error": True,
"reason": "disk full",
"default_rescue_catches_standard_error": True,
}
actual = {
"caught_type": caught_type,
"inherits_standard_error": is_std,
"reason": reason_msg,
"default_rescue_catches_standard_error": issubclass(FileSaveError, StandardErrorRb),
}
return {
"name": "raise_forms_and_custom_error",
"summary": "核验继承 StandardError 的自定义异常 FileSaveError 包装原始异常 $! 与默认 rescue 捕获层级",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_catch_throw_nonlocal_exit():
class ThrowSignal(BaseException):
def __init__(self, tag, value=None):
self.tag = tag
self.value = value
inputs = iter(["Ruby on Rails", "3", "!", "Just Ruby"])
collected = []
def prompt_and_get(label):
res = next(inputs)
if res == "!":
raise ThrowSignal("quitRequested", "aborted_at_sex")
return f"{label}{res}"
catch_result = None
try:
collected.append(prompt_and_get("Name: "))
collected.append(prompt_and_get("Age: "))
collected.append(prompt_and_get("Sex: "))
collected.append("unreachable")
except ThrowSignal as sig:
if sig.tag == "quitRequested":
catch_result = sig.value
else:
raise
after_catch = prompt_and_get("Name:")
expected = {
"collected_before_throw": ["Name: Ruby on Rails", "Age: 3"],
"catch_result": "aborted_at_sex",
"after_catch": "Name:Just Ruby",
}
actual = {
"collected_before_throw": collected,
"catch_result": catch_result,
"after_catch": after_catch,
}
return {
"name": "catch_throw_nonlocal_exit",
"summary": "核验 catch/throw 按符号标签跳出多层调用栈并传递返回值的正常控制流语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_begin_rescue_else_ensure_flow(),
case_retry_with_bounded_fallback(),
case_raise_forms_and_custom_error(),
case_catch_throw_nonlocal_exit(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 4 个确定性用例全部通过,验证异常与无异常执行轨迹、retry 回退与上限保护、FileSaveError 包装及 catch/throw 跳转。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
当前源码 SHA256:ecf6d9fd635746bc151bc930ef222d640c2eaa492ccf8574464684b2f706c08c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
ZIP SHA256:ed53fdef1482f1b98485030bcbb17ab034a05111d22a6d0b6bd31c59a0158fe9
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Ruby 中,为什么自定义业务异常应该继承 `StandardError` 而不是直接继承 `Exception`?
展开参考解答
因为不指定类型的 `rescue` 默认只捕获 `StandardError` 及其子类;直接继承 `Exception` 会导致常规 `rescue` 漏捕,反而诱使开发者写出危险的 `rescue Exception`(会误拦截 Ctrl+C 的 `Interrupt` 和 `SystemExit`)。