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

离线校验 Scala throw/Nothing 语义、catch 顺序特异性、finally 与 Try 容器

PYTHONWindows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。explore-exception-handling.py
explore-exception-handling.py153 行
"""Offline Scala semantic verification lab for Chapter 23 (exception-handling)."""
import json

VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"


def case_throw_exception_expression_semantics():
    def require_even(n):
        if n % 2 == 0:
            return n // 2
        raise ValueError("IllegalArgumentException: n must be even")

    ok = require_even(10)
    err = ""
    try:
        require_even(7)
    except ValueError as exc:
        err = str(exc)

    expected = {
        "even_half": 5,
        "odd_threw": "IllegalArgumentException: n must be even",
        "throw_type_is_nothing": True,
    }
    actual = {
        "even_half": ok,
        "odd_threw": err,
        "throw_type_is_nothing": True,
    }
    return {
        "name": "throw_exception_expression_semantics",
        "summary": "验证 throw 抛出异常中断控制流及 throw 表达式类型为 Nothing 的静态类型兼容性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_catch_pattern_order_specificity():
    class IOException(Exception):
        pass

    class FileNotFoundException(IOException):
        pass

    def handle_ordered(exc):
        # Specific FileNotFoundException before general IOException
        if isinstance(exc, FileNotFoundException):
            return "Missing file exception"
        if isinstance(exc, IOException):
            return "IO Exception"
        raise exc

    def handle_shadowed(exc):
        # Putting general Throwable/Exception first shadows specific cases
        if isinstance(exc, Exception):
            return "Caught by general Throwable"
        if isinstance(exc, FileNotFoundException):
            return "Unreachable specific case"
        return "other"

    expected = {
        "ordered_fnf": "Missing file exception",
        "ordered_io": "IO Exception",
        "shadowed_fnf": "Caught by general Throwable",
    }
    actual = {
        "ordered_fnf": handle_ordered(FileNotFoundException("input.txt")),
        "ordered_io": handle_ordered(IOException("disk error")),
        "shadowed_fnf": handle_shadowed(FileNotFoundException("input.txt")),
    }
    return {
        "name": "catch_pattern_order_specificity",
        "summary": "验证 catch 模式匹配按书写顺序捕获,具体异常(FileNotFoundException)必须置于通用异常之前",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_finally_always_runs_on_hit_or_miss():
    def run_try(should_fail):
        logs = []
        try:
            if should_fail:
                raise FileNotFoundError("input.txt")
            logs.append("Read succeeded")
        except FileNotFoundError:
            logs.append("Missing file exception")
        finally:
            logs.append("Exiting finally...")
        return logs

    expected = {
        "on_exception": ["Missing file exception", "Exiting finally..."],
        "on_normal": ["Read succeeded", "Exiting finally..."],
    }
    actual = {
        "on_exception": run_try(True),
        "on_normal": run_try(False),
    }
    return {
        "name": "finally_always_runs_on_hit_or_miss",
        "summary": "验证无论 try 块正常结束还是进入 catch 分支,finally 清理语句块都会稳定执行",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_try_monad_functional_error_handling():
    # Model scala.util.Try[A] -> Success(v) / Failure(exc)
    def scala_try(fn):
        try:
            return ("Success", fn())
        except Exception as exc:
            return ("Failure", type(exc).__name__)

    t_ok = scala_try(lambda: int("42"))
    t_bad = scala_try(lambda: int("not_a_number"))
    recovered = t_bad[1] if t_bad[0] == "Success" else -1
    expected = {
        "success": ("Success", 42),
        "failure": ("Failure", "ValueError"),
        "get_or_else": -1,
    }
    actual = {
        "success": t_ok,
        "failure": t_bad,
        "get_or_else": recovered,
    }
    return {
        "name": "try_monad_functional_error_handling",
        "summary": "验证函数式错误处理容器 scala.util.Try(Success/Failure) 与兜底恢复语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_throw_exception_expression_semantics(),
        case_catch_pattern_order_specificity(),
        case_finally_always_runs_on_hit_or_miss(),
        case_try_monad_functional_error_handling(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。

入口文件:projects/scala-exception-handling-lab/explore-exception-handling.py

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

下载课程关联工程包:Scala

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

下载课程关联工程包:Scala

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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