蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Ruby begin/rescue/else/ensure、有界 retry、自定义异常与 catch/throw

PYTHONWindows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。explore-exceptions.py
explore-exceptions.py169 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。

入口文件:projects/ruby-exceptions-lab/explore-exceptions.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-exceptions.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Ruby

课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip

下载课程关联工程包:Ruby

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2452.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习