蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python3 错误和异常

沿着一次读取和校验的流程,定位错误、选择处理分支并释放资源。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先确定错误发生的阶段

读诊断时先定位文件、行和异常类型。解析器发现循环头漏写冒号时会给出 SyntaxError,标记是发现问题的位置,修复点可能在它前面。如果在运行中调用 compile 或导入有语法问题的模块,外层可以捕获该异常。

语法合法的表达式也会失败。除数为零触发 ZeroDivisionError,使用未绑定的名字触发 NameError,文本和整数直接相加触发 TypeError。先读回溯末行的类型和消息,再沿调用帧找到输入和运算的位置。

用 try 保护可能失败的操作,用 except 处理已知错误,用 else 放成功后的操作,用 finally 清理。raise 主动报告错误。assert 表达调试期不变量,条件为假时通常抛出 AssertionError。优化编译可以省略整个断言,外部输入校验应使用显式条件和异常。

只捕获当前步骤能处理的错误

读取整数时只捕获 ValueError,再请读者重新输入。末尾没有任何输入会得到 EOFError。终端中断通常表现为 KeyboardInterrupt,它属于 BaseException 分支,普通的 except Exception 不会拦住它。

try 中发生异常后,剩余语句跳过。普通 except 从上到下找首个匹配项,可以用括号内的异常类型元组共用一个处理器。子类也能匹配基类,具体类型宜排在宽泛类型前面。调用函数深处的未处理异常会沿调用栈返回。

读取文件遇到 OSError 可报告路径或权限,转换文本遇到 ValueError 可报告输入问题。无类型的 except 会连中断和退出都捕获且必须放最后。只为记录故障时,裸 raise 会继续传播当前异常。

分开成功分支和清理分支

把打开文件留在 try 里,把计数留在 else 中,这样读取阶段的 OSError 不会被误报成打开失败。else 位于处理器之后,在 try 正常走到末尾时运行。提前 return、break、continue 都会跳过它。

finally 在控制流离开时运行,包括正常结束、命中处理器、异常继续外传或提前返回。处理器和 else 内的新异常也会经过清理,同一组普通 except 不会重新匹配它们。系统强制终止进程时,无法依赖 Python 完成清理。

用 12 除以 3、除以 0 和文本作除数分别观察成功分支、已处理错误和外传错误,三条路径均留下清理记录。避免在 finally 中 return,清理中的返回可以覆盖结果或吞掉原异常。清理本身失败时,新异常会保留原异常作为上下文。

主动报告错误并保留原因

校验配额时,超限可用 raise ValueError(message) 退出当前路径。Python 3 接受 BaseException 的实例或可无参构造的子类,裸 raise 需要正在处理的异常。将底层异常转换为上层异常时,可用 raise 新异常 from 原异常明确记录原因。

旧 Python 2 资料里的逗号写法曾用来传异常参数和回溯。迁移时改为构造实例后抛出,确需指定已有回溯时可用 with_traceback(tb)。Python 3 会拒绝旧式逗号写法。

给模块定义一个继承 Exception 的基础错误,再细分输入错误和状态转换错误。子类可保存原始输入、旧状态与目标状态,并调用 super().__init__(message) 让 args 和文本诊断保留消息。Error 后缀是一种命名惯例。

让文件自行退出上下文

直接遍历 open(...) 返回的文件并没有显式规定关闭时机。需要确定关闭时机时,在 with 内迭代。文件成功进入上下文后,即使读取或处理时抛出异常,也会执行退出逻辑并关闭文件。

本站实例用自建临时文件检查两条路径。正常读取两行时退出后 closed 为 True。处理失败时先关闭文件,再由外层收到 RuntimeError。如果打开文件失败,程序尚未进入文件上下文,应在调用处决定如何报告。

分支与可观察结果

场景可观察结果检查点
合法整数返回整数此前的无效输入可重试
打开缺失文件FileNotFoundError是 OSError 的子类
try 内提前返回跳过 else,进入 finally清理后的原返回值仍可交给调用者
除数为零命中 ZeroDivisionError 处理器不进入 else,仍清理
不支持的除数类型TypeError 传给外层先执行 finally
成功进入文件上下文退出时文件关闭正常退出和异常退出均可检查 closed

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 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 环境

当前源码 SHA256:e8ef07dbbc07f164b76ce16da80efa64e291e177b11095b5cd21ed876f18492a

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据