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

运行本章核心实例

PYTHON本地 Python 环境python3-errors-execptions.py
python3-errors-execptions.py298 行
"""蓝色天空网 mbsky.com | Run bounded exception examples on owned inputs."""
from pathlib import Path
from tempfile import TemporaryDirectory
import os
import subprocess
import sys
import traceback

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


def read_quantity():
    while True:
        try:
            return int(input("quantity> "))
        except ValueError:
            print("try an integer")


def calculate(divisor, steps):
    try:
        steps.append("try")
        value = 12 / divisor
    except ZeroDivisionError:
        steps.append("zero")
        return None
    else:
        steps.append("else")
        return value
    finally:
        steps.append("finally")


def read_count(path):
    try:
        stream = path.open(encoding="utf-8")
    except OSError as error:
        return "open", type(error).__name__
    else:
        with stream:
            return "lines", sum(1 for line in stream)


def read_integer_file(path):
    try:
        with path.open(encoding="utf-8") as stream:
            return "value", int(stream.readline().strip())
    except OSError as error:
        return "open", type(error).__name__
    except ValueError:
        return "conversion", None


class BookingError(Exception):
    """Base error raised by the booking workflow."""


class QuantityError(BookingError):
    def __init__(self, value, message):
        super().__init__(message)
        self.value = value


class TransitionError(BookingError):
    def __init__(self, previous, target):
        super().__init__(f"cannot move from {previous} to {target}")
        self.previous = previous
        self.target = target


def reserve(quantity):
    if quantity > 8:
        raise QuantityError(quantity, "capacity is eight")
    return quantity


def confirm(state):
    if state != "held":
        raise TransitionError(state, "confirmed")
    return "confirmed"


def run_examples():
    checks = Checks()
    bad_loop = "for stop in range(1) print(stop)"
    try:
        compile(bad_loop, "owned-schedule.py", "exec")
    except SyntaxError as error:
        checks.eq("parser diagnostic", (error.filename, error.lineno, error.text.strip()),
                  ("owned-schedule.py", 1, bad_loop))

    def unbound():
        return missing_rate

    checks.raises("unbound name", NameError, unbound)
    checks.raises("text plus integer", TypeError, lambda: "dock" + 3)
    checks.raises("zero in called frame", ZeroDivisionError, lambda: 12 / 0)

    def nested_total(divisor):
        return 12 / divisor

    try:
        nested_total(0)
    except ZeroDivisionError as error:
        checks.eq("traceback deepest frame", traceback.extract_tb(error.__traceback__)[-1].name,
                  "nested_total")

    invocation = [sys.executable, "-I", "-B", "-X", "utf8", __file__, "--quantity"]
    retry = subprocess.run(invocation, input="dock\n4\n", text=True, encoding="utf8",
                           capture_output=True, timeout=10)
    checks.eq("stdin retry status", retry.returncode, 0)
    checks.eq("stdin retry then four", retry.stdout, "quantity> try an integer\nquantity> accepted=4\n")
    eof = subprocess.run(invocation, input="", text=True, encoding="utf8", capture_output=True, timeout=10)
    checks.eq("stdin EOF status", eof.returncode, 2)
    checks.eq("stdin EOF separately reported", eof.stdout, "quantity> end of input\n")

    for failure in (TypeError, NameError, RuntimeError):
        try:
            raise failure("fixture")
        except (RuntimeError, TypeError, NameError) as error:
            checks.eq("tuple branch " + failure.__name__, type(error).__name__, failure.__name__)
        except Exception:
            raise AssertionError("specific handler should win")

    try:
        try:
            raise KeyboardInterrupt("owned signal simulation")
        except Exception:
            raise AssertionError("KeyboardInterrupt should escape Exception")
    except:
        checks.eq("bare handler sees interrupt", type(sys.exception()).__name__, "KeyboardInterrupt")
        original = sys.exception()
        try:
            raise
        except KeyboardInterrupt as error:
            checks.eq("bare re-raise keeps active instance", error is original, True)

    steps = []
    checks.eq("division success", calculate(3, steps), 4.0)
    checks.eq("success order", steps, ["try", "else", "finally"])
    steps = []
    checks.eq("division zero handled", calculate(0, steps), None)
    checks.eq("zero order", steps, ["try", "zero", "finally"])
    steps = []
    checks.raises("division type propagates", TypeError, lambda: calculate("dock", steps))
    checks.eq("type error cleanup order", steps, ["try", "finally"])

    for stage in ("try", "except", "else"):
        steps = []
        try:
            try:
                if stage == "try":
                    raise KeyboardInterrupt()
                if stage == "except":
                    raise ValueError("invalid quantity")
            except ValueError:
                raise RuntimeError("handler")
            except RuntimeError:
                steps.append("incorrect sibling")
            else:
                raise RuntimeError("success path")
            finally:
                steps.append("cleanup")
        except (KeyboardInterrupt, RuntimeError) as error:
            expected = "KeyboardInterrupt" if stage == "try" else "RuntimeError"
            checks.eq("outer exception from " + stage, type(error).__name__, expected)
        checks.eq("cleanup on exit from " + stage, steps, ["cleanup"])

    def early_return(steps):
        try:
            return 9
        except ValueError:
            steps.append("except")
        else:
            steps.append("else")
        finally:
            steps.append("finally")

    steps = []
    checks.eq("return value retained", early_return(steps), 9)
    checks.eq("return skips else", steps, ["finally"])
    for action in ("continue", "break"):
        steps = []
        for _ in range(1):
            try:
                if action == "continue":
                    continue
                break
            except ValueError:
                steps.append("except")
            else:
                steps.append("else")
            finally:
                steps.append("finally")
        checks.eq(action + " skips else", steps, ["finally"])

    def override():
        try:
            raise ValueError("lost")
        finally:
            return "replacement"

    checks.eq("finally return masks active error", override(), "replacement")

    try:
        try:
            raise ValueError("original")
        finally:
            raise RuntimeError("cleanup failed")
    except RuntimeError as error:
        checks.eq("cleanup error keeps context", str(error.__context__), "original")

    checks.eq("threshold accepted", reserve(8), 8)
    try:
        reserve(9)
    except BookingError as error:
        checks.eq("base class catches quantity subtype", type(error).__name__, "QuantityError")
        checks.eq("custom message and value", (str(error), error.args, error.value),
                  ("capacity is eight", ("capacity is eight",), 9))
    checks.eq("allowed transition", confirm("held"), "confirmed")
    try:
        confirm("new")
    except TransitionError as error:
        checks.eq("transition metadata", (error.previous, error.target), ("new", "confirmed"))

    try:
        raise FileNotFoundError
    except OSError as error:
        checks.eq("raise class instantiates", (type(error).__name__, error.args),
                  ("FileNotFoundError", ()))
    try:
        try:
            int("dock")
        except ValueError as cause:
            raise QuantityError("dock", "quantity expected") from cause
    except QuantityError as error:
        checks.eq("explicit exception chain", type(error.__cause__).__name__, "ValueError")

    checks.raises("old comma syntax rejected", SyntaxError,
                  lambda: compile("raise ValueError, 'old'", "<history>", "exec"))
    try:
        nested_total(0)
    except ZeroDivisionError as error:
        replacement = ValueError("converted").with_traceback(error.__traceback__)
        checks.eq("attach existing traceback", replacement.__traceback__ is error.__traceback__, True)

    text = "assert quota >= 0, 'negative quota'"
    checks.raises("assert false with optimization off", AssertionError,
                  lambda: exec(compile(text, "<owned>", "exec", optimize=0), {"quota": -1}))
    checks.eq("optimized assertion omitted", exec(compile(text, "<owned>", "exec", optimize=1),
                                                  {"quota": -1}), None)

    with TemporaryDirectory() as directory:
        path = Path(directory) / "orders.txt"
        path.write_text("4\ndock\n", encoding="utf-8")
        missing = path.with_name("missing.txt")
        checks.eq("normal file count in else", read_count(path), ("lines", 2))
        checks.eq("missing file handled on open", read_count(missing), ("open", "FileNotFoundError"))
        checks.eq("file integer", read_integer_file(path), ("value", 4))
        path.write_text("dock\n", encoding="utf-8")
        checks.eq("file invalid integer", read_integer_file(path), ("conversion", None))
        checks.eq("file open error distinct", read_integer_file(missing), ("open", "FileNotFoundError"))
        path.write_bytes(b"\xff")
        checks.raises("read-stage decode error escapes open handler", UnicodeDecodeError,
                      lambda: read_count(path))
        path.write_text("4\ndock\n", encoding="utf-8")
        with path.open(encoding="utf-8") as stream:
            checks.eq("managed iteration", [line.strip() for line in stream], ["4", "dock"])
        checks.eq("closed on normal exit", stream.closed, True)
        try:
            with path.open(encoding="utf-8") as stream:
                raise RuntimeError("owned processing failure")
        except RuntimeError as error:
            checks.eq("error outside with", str(error), "owned processing failure")
        checks.eq("closed on exceptional exit", stream.closed, True)
        unmanaged = path.open(encoding="utf-8")
        try:
            list(unmanaged)
            checks.eq("iteration does not close a retained stream", unmanaged.closed, False)
        finally:
            unmanaged.close()
        checks.eq("manual close", unmanaged.closed, True)

    checks.finish("python3-errors-execptions", runtime=sys.version, operating_system=os.name,
                  interrupt="Explicit KeyboardInterrupt simulation, not a physical terminal keypress")


if __name__ == "__main__":
    if sys.argv[1:] == ["--quantity"]:
        try:
            print(f"accepted={read_quantity()}")
        except EOFError:
            print("end of input")
            sys.exit(2)
    else:
        run_examples()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-errors-execptions.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-errors-execptions.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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