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

运行离线 Python 校验:Kotlin try 表达式、Nothing、临时文件 use 自动关闭与 runCatching

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-exception.py
explore-exception.py276 行
"""Offline Kotlin 2.x semantic verifier for Chapter 34: Exception Handling."""
import json
from pathlib import Path
import tempfile

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


def case_try_catch_finally_and_expression():
    logs = []
    for raw in ("42", "kotlin", None):
        try:
            if raw is None:
                raise TypeError("NullPointerException")
            val = int(raw)
            logs.append(f"{raw} 转换成功:{val}")
        except ValueError:
            logs.append(f'数字格式错误:For input string: "{raw}"')
        except TypeError:
            logs.append("遇到 null 值")
        finally:
            logs.append("--- 处理完一轮 ---")
    logs.append("循环结束,程序继续运行")

    def parse_age(text: str) -> int:
        try:
            return int(text)
        except ValueError:
            return -1

    finally_ran = False

    def parse_with_finally() -> int:
        nonlocal finally_ran
        try:
            res = int("20")
        finally:
            finally_ran = True
        return res

    actual = {
        "loop_logs": logs,
        "parse_age_ok": parse_age("18"),
        "parse_age_bad": parse_age("kotlin"),
        "try_with_finally_val": parse_with_finally(),
        "finally_ran": finally_ran,
    }
    expected = {
        "loop_logs": [
            "42 转换成功:42",
            "--- 处理完一轮 ---",
            '数字格式错误:For input string: "kotlin"',
            "--- 处理完一轮 ---",
            "遇到 null 值",
            "--- 处理完一轮 ---",
            "循环结束,程序继续运行",
        ],
        "parse_age_ok": 18,
        "parse_age_bad": -1,
        "try_with_finally_val": 20,
        "finally_ran": True,
    }
    return {
        "name": "try_catch_finally_and_expression",
        "summary": "Verify top-down catch matching, finally execution, and try-as-expression return value",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_throw_nothing_and_custom_exception():
    class InvalidSiteNameException(Exception):
        def __init__(self, site_name: str, cause: Exception | None = None):
            super().__init__(f"非法的站点名称:{site_name}")
            self.site_name = site_name
            self.cause = cause

    def fail(msg: str):
        raise ValueError(msg)

    def check_age(age: int) -> str:
        if age < 0:
            fail(f"年龄不能为负数:{age}")
        return f"年龄合法:{age}"

    def register_site(name: str) -> str:
        if not name.lower().startswith("mbsky"):
            raise InvalidSiteNameException(name)
        return f"注册成功:{name}"

    neg_err = None
    try:
        check_age(-1)
    except ValueError as exc:
        neg_err = str(exc)

    custom_err = None
    try:
        register_site("example")
    except InvalidSiteNameException as exc:
        custom_err = f"注册失败:{exc},问题字段:{exc.site_name}"

    def read_config(path: str) -> str:
        if not path:
            raise OSError("配置路径为空")
        return f"配置来自 {path}"

    io_err = None
    try:
        read_config("")
    except OSError as exc:
        io_err = str(exc)

    actual = {
        "age_ok": check_age(18),
        "age_neg_err": neg_err,
        "register_ok": register_site("mbsky-app"),
        "custom_err": custom_err,
        "config_ok": read_config("app.conf"),
        "config_err": io_err,
        "kotlin_has_checked_exceptions": False,
    }
    expected = {
        "age_ok": "年龄合法:18",
        "age_neg_err": "年龄不能为负数:-1",
        "register_ok": "注册成功:mbsky-app",
        "custom_err": "注册失败:非法的站点名称:example,问题字段:example",
        "config_ok": "配置来自 app.conf",
        "config_err": "配置路径为空",
        "kotlin_has_checked_exceptions": False,
    }
    return {
        "name": "throw_nothing_and_custom_exception",
        "summary": "Verify Nothing-returning fail(), custom exception context fields, and unchecked @Throws IOException",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_use_auto_close_temp_file():
    closed_on_error = False

    class TrackedResource:
        def __enter__(self):
            return self

        def __exit__(self, exc_type, exc, tb):
            nonlocal closed_on_error
            closed_on_error = True
            return False

    with tempfile.TemporaryDirectory() as tmp:
        fp = Path(tmp) / "sample.txt"
        with fp.open("w", encoding="utf-8") as writer:
            writer.write("Hello Kotlin\n")
            writer.write("Hello Exceptions")
        with fp.open("r", encoding="utf-8") as reader:
            lines = [ln.rstrip("\n") for ln in reader]
        with fp.open("r", encoding="utf-8") as reader:
            line_count = sum(1 for _ in reader)

    errored = False
    try:
        with TrackedResource():
            raise RuntimeError("boom")
    except RuntimeError:
        errored = True

    actual = {
        "lines": lines,
        "line_count": line_count,
        "closed_even_on_exception": errored and closed_on_error,
    }
    expected = {
        "lines": ["Hello Kotlin", "Hello Exceptions"],
        "line_count": 2,
        "closed_even_on_exception": True,
    }
    return {
        "name": "use_auto_close_temp_file",
        "summary": "Verify use/useLines automatic close on normal exit and exception exit with a real temp file",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_run_catching_and_cancellation_guard():
    class CancellationException(Exception):
        pass

    class Result:
        def __init__(self, value=None, error: Exception | None = None):
            self._value = value
            self._error = error

        @property
        def is_success(self) -> bool:
            return self._error is None

        @property
        def is_failure(self) -> bool:
            return self._error is not None

        def get_or_null(self):
            return self._value if self.is_success else None

        def get_or_default(self, default):
            return self._value if self.is_success else default

        def get_or_else(self, fn):
            return self._value if self.is_success else fn(self._error)

        def on_failure(self, fn):
            if self.is_failure:
                fn(self._error)
            return self

    def run_catching(fn) -> Result:
        try:
            return Result(value=fn())
        except Exception as exc:
            return Result(error=exc)

    ok = run_catching(lambda: int("42"))
    bad = run_catching(lambda: int("bad"))
    failure_hooks = []
    run_catching(lambda: int("x")).on_failure(lambda e: failure_hooks.append(type(e).__name__))

    # Safe coroutine wrapper rethrows CancellationException
    cancelled_propagated = False
    try:
        res = run_catching(lambda: (_ for _ in ()).throw(CancellationException("cancelled")))
        if isinstance(res._error, CancellationException):
            raise res._error
    except CancellationException:
        cancelled_propagated = True

    actual = {
        "ok": [ok.is_success, ok.get_or_null()],
        "bad": [bad.is_failure, bad.get_or_null(), bad.get_or_default(-1)],
        "fallback": bad.get_or_else(lambda _e: "兜底(NumberFormatException)"),
        "on_failure_hook": failure_hooks,
        "cancellation_rethrown": cancelled_propagated,
    }
    expected = {
        "ok": [True, 42],
        "bad": [True, None, -1],
        "fallback": "兜底(NumberFormatException)",
        "on_failure_hook": ["ValueError"],
        "cancellation_rethrown": True,
    }
    return {
        "name": "run_catching_and_cancellation_guard",
        "summary": "Verify Result/runCatching methods and CancellationException rethrow discipline",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_try_catch_finally_and_expression(),
        case_throw_nothing_and_custom_exception(),
        case_use_auto_close_temp_file(),
        case_run_catching_and_cancellation_guard(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。

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

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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