异常类别、捕获顺序与清理
运行正常与失败路径,区分异常实例、诊断字段、警告过滤和历史写法。
学完这一章,你能够
- 运行正常与失败路径,区分异常实例、诊断字段、警告过滤和历史写法。
异常离开当前执行路径
异常是可抛出的对象。出错后从当前调用栈寻找可匹配处理器,找不到就向上层传播。except 按代码次序匹配,也能匹配指定类型的子类。建议先写更具体的类型。
SystemExit、KeyboardInterrupt 和 GeneratorExit 属于 BaseException 分支,通常让它们传播。裸 except 会一并捕获这些类别,窄范围捕获更容易保留失败原因。
把成功分支和清理分开
try 只包住预计失败的操作,else 在 try 正常完成时运行。finally 用于清理,无论正常、已捕获、传播异常或提前返回都会进入;在 finally 中抛出新异常或返回会改变原来的结果。
文件示例在新建的临时目录验证成功写入、只读文件写入被拒绝以及异常向外传播。文件用 with 或明确的 finally 关闭,清理消息不能冒充原操作的异常原因。
读错误字段与抛出自定义异常
现代捕获使用 except 类型 as 名称,可检查 args、errno 和 filename 等字段。args 通常是构造参数元组,具体字段取决于异常类型。
现代写法用 raise 某个异常实例,或在处理器内裸 raise 重抛当前异常。字符串异常和逗号形式的 raise 是历史语法;2.7.18 已不支持字符串异常。用 raise 新异常 from 原异常显式保留因果。
断言与警告
assert 适合核对程序内部约定,启用时失败会抛 AssertionError。优化模式可能省掉断言,输入校验应显式处理。
warnings.warn 发出警告,过滤器决定是否忽略、展示或升级为异常。下面在子进程中临时调整过滤,只核对表中的类别。
异常与警告类别逐项说明
| 名称 | 用途 | 版本或核对条件 |
| BaseException | 所有可抛出异常的根类。 | 同时检查 Exception 和三个退出类的继承。 |
| SystemExit | sys.exit 请求终止,异常携带 code。 | 隔离子进程实际退出码为 7。 |
| KeyboardInterrupt | 通常由中断触发,直接从 BaseException 派生。 | 安全注入观察捕获边界,真实按键另验。 |
| Exception | 应用程序异常通常从这一支派生。 | 检查常见错误可由 Exception 捕获,而退出信号不在这一支。 |
| StopIteration | 迭代器耗尽时由 next 产生。 | 使用空迭代器。 |
| GeneratorExit | 关闭已启动的生成器时注入。 | 运行一次 next 后调用 close,生成器记录清理。 |
| StandardError | 2.7 的内置错误分组,3.x 已移除。 | 现代只检查名称不存在,不用不存在的类捕获。 |
| ArithmeticError | 数值运算异常的公共父类。 | 检查除零、溢出及浮点异常的继承。 |
| FloatingPointError | 为浮点异常保留的类型,常规 Python 算术很少直接触发。 | 显式注入以观察异常分组。 |
| OverflowError | 某些受范围限制的数值运算或转换发生溢出。 | math.exp 的大输入触发;普通 int 运算不按固定机器位数截断。 |
| ZeroDivisionError | 除数或取模分母为零时触发。 | 实测除法和取模两个分支。 |
| AssertionError | 启用断言时,assert 条件为假会引发。 | 普通运行检查实际异常,另核对 -O 下不运行断言。 |
| AttributeError | 属性读取或赋值不支持。 | 从普通对象读取不存在的属性。 |
| EOFError | input 在没有下一行可读时触发。 | 空标准输入流。 |
| EnvironmentError | 2.7 的系统环境错误基类,现代是 OSError 的兼容别名。 | Windows CPython 3.12 检查对象身份。 |
| IOError | 历史 I/O 异常名称,现代是 OSError 的别名。 | 检查别名并触发实际缺文件异常。 |
| OSError | 由操作系统相关操作报告,可细分为权限、缺文件等。 | 临时目录内缺文件产生 FileNotFoundError,保留其父类关系。 |
| WindowsError | 历史 Windows 系统调用错误名称,当前 Windows CPython 仍可见为 OSError 的兼容别名。 | 检查本平台的别名,不把它当可移植的捕获名。 |
| ImportError | 加载模块或解析 from 导入的名称失败。 | 导入已有模块中不存在的名字。 |
| LookupError | 索引与键查找错误的父类。 | 检查 IndexError 与 KeyError 的继承。 |
| IndexError | 序列索引越界。 | 读取空列表的索引 0。 |
| KeyError | 映射找不到指定键。 | 读取空字典中的指定键。 |
| MemoryError | 内存分配失败可能触发。 | 安全显式注入验证捕获,实际内存耗尽不做测试。 |
| NameError | 当前名字查找规则下找不到名称。 | 读取从未绑定的名称。 |
| UnboundLocalError | 函数读取尚未绑定的局部变量,是 NameError 子类。 | 函数先读再写同一局部名称。 |
| ReferenceError | 通过弱引用代理访问已消失的对象时触发。 | 释放临时对象并用代理读取属性。 |
| RuntimeError | 在没有更具体类别时报告运行错误。 | 生成器内逸出的 StopIteration 会变成 RuntimeError。 |
| NotImplementedError | 实现尚未提供某项行为时可主动抛出。 | 基类方法主动抛出,与 NotImplemented 单例分开。 |
| SyntaxError | 解析源代码失败,可带文件名与行号。 | 对本站短文本用 compile 检查,不运行错误代码。 |
| IndentationError | 缺少缩进或缩进层级无效的语法错误。 | 编译缺少缩进的短代码。 |
| TabError | 制表符与空格混合导致缩进解释不一致。 | 编译刻意混合缩进的短文本。 |
| SystemError | 解释器或扩展检测到内部错误时可能报告。 | 仅显式注入验证分类,不制造解释器损坏。 |
| TypeError | 操作或调用接受的类型与实际输入不符。 | 相加两个不兼容类型。 |
| ValueError | 参数类型可用但具体值不合法。 | 把非数字文本传给 int。 |
| UnicodeError | Unicode 相关异常的共同父类,是 ValueError 子类。 | 验证编解码错误的继承。 |
| UnicodeDecodeError | 从字节解码为文本失败。 | 严格解码不完整的 UTF-8。 |
| UnicodeEncodeError | 文本无法用指定编码表示。 | 用 ASCII 严格编码中文。 |
| UnicodeTranslateError | Unicode 转换异常,可携带输入和位置等字段。 | 显式构造并抛出观察字段,普通 str.translate 不一定产生它。 |
| Warning | 警告类别的父类,过滤器可以显示、忽略或把它当异常。 | 观察同一警告的忽略和 error 模式。 |
| DeprecationWarning | 主要提醒开发者接口被弃用,默认显示规则取决于来源。 | 在受控过滤器中用明确类别发出。 |
| FutureWarning | 主要提醒应用用户可见行为将有变化。 | 在受控过滤器中用明确类别发出。 |
| OverflowWarning | 旧版本关于整数溢出或自动提升的类别,当前没有此内置名称。 | 检查 Python 3.12 中该名称缺席。 |
| PendingDeprecationWarning | 提示计划弃用,通常默认隐藏。 | 临时设置 always 后观察。 |
| RuntimeWarning | 用于可疑的运行期行为。 | 显式发出并检查类别。 |
| SyntaxWarning | 用于可疑但仍能编译的语法。 | 编译使用 is 与数字字面量比较的短代码。 |
| UserWarning | warnings.warn 的默认类别。 | 省略 category 并观察警告对象。 |
运行异常分类、清理及诊断实验
展开查看收起
import json
def report(name, value):
print(json.dumps([name, value], ensure_ascii=True))
def error_name(action):
try:
action()
except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError) as error:
return type(error).__name__
return None
import builtins
import gc
import io
import math
import os
import stat
import subprocess
import sys
import warnings
import weakref
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
def caught(action):
try:
action()
except BaseException as error:
return [type(error).__name__,isinstance(error,Exception)]
return [None,False]
def inject(error):
raise error
def child(*args):
proc=subprocess.run([sys.executable,"-I","-B","-X","utf8",*args],capture_output=True)
return proc.returncode,proc.stdout.decode("utf8").strip(),proc.stderr.decode("utf8").strip()
def assert_failed():
assert 4 == 5
def unbound():
points += 1
def bad_generator():
if False:
yield 0
raise StopIteration
class Entry:
count=4
def not_implemented():
raise NotImplementedError("supply loader")
actions=[]
def closing_generator():
try:
yield 4
except GeneratorExit:
actions.append("GeneratorExit")
raise
finally:
actions.append("cleanup")
def warning(category):
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter("always")
if category is None:
warnings.warn("sample warning")
else:
warnings.warn("sample warning",category)
return type(recorded[0].message).__name__
def syntax_warning():
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter("always",SyntaxWarning)
compile("x = value is 7", "<owned-warning>", "exec")
return [type(x.message).__name__ for x in recorded]
with TemporaryDirectory(prefix="mbsky-exceptions-",dir=Path.cwd()) as directory:
root=Path(directory).resolve()
target=root/"measurement.txt"
file_flow=[]
try:
with open(target,"w",encoding="utf8",newline="") as stream:
stream.write("北站 7")
except OSError:
file_flow.append("failure")
else:
file_flow.append("success")
denied=None
try:
target.chmod(stat.S_IREAD)
try:
with open(target,"w",encoding="utf8") as stream:
stream.write("forbidden")
except OSError as error:
denied=[type(error).__name__,Path(error.filename).name,isinstance(error,PermissionError)]
finally:
target.chmod(stat.S_IREAD|stat.S_IWRITE)
missing=root/"missing.txt"
missing_result=caught(missing.read_bytes)
report("file_write",[file_flow,target.read_text(encoding="utf8"),denied])
def flow(value):
trace=[]
try:
trace.append("try")
if value:
raise value
except KeyError:
trace.append("first specific")
except (ValueError,TypeError):
trace.append("tuple")
else:
trace.append("else")
finally:
trace.append("finally")
return trace
bare=[]
try:
raise KeyboardInterrupt("injected")
except:
bare.append("caught BaseException")
def nested_failure():
with open(target,"r",encoding="utf8") as stream:
try:
raise ValueError("owned bad record")
finally:
cleanup.append("inner finally")
streams.append(stream)
cleanup=[]
streams=[]
try:
nested_failure()
except ValueError as error:
cleanup.append(type(error).__name__)
def returning():
try:
return 9
finally:
cleanup.append("return cleanup")
result=returning()
report("flow",[flow(None),flow(KeyError("missing")),flow(ValueError("bad")),
flow(TypeError("bad")),bare])
report("cleanup",[cleanup,[s.closed for s in streams],result])
details=[]
try:
int("north")
except ValueError as error:
details=[type(error).__name__,len(error.args),"north" in str(error)]
try:
missing.read_bytes()
except OSError as error:
details.append([type(error).__name__,error.errno,Path(error.filename).name])
report("exception_fields",details)
class LevelError(RuntimeError):
def __init__(self, level):
super().__init__("level must be positive",level)
self.level=level
def validate(level):
if level<1:
raise LevelError(level)
return level
def convert(raw):
try:
return int(raw)
except ValueError as previous:
raise LevelError(0) from previous
def rethrow():
try:
raise ValueError("rethrow")
except ValueError:
raise
report("raise_and_chain",[validate(4),caught(lambda:validate(0)),caught(rethrow),
caught(lambda:inject("unsupported string"))])
try:
convert("north")
except LevelError as error:
report("custom_exception",[isinstance(error,RuntimeError),error.args,error.level,
type(error.__cause__).__name__,error.__traceback__ is not None])
with patch("sys.stdin",io.StringIO("")):
eof=caught(input)
value=Entry()
proxy=weakref.proxy(value)
del value
gc.collect()
generator=closing_generator()
first_yield=next(generator)
generator.close()
exit_code=child("-c","import sys;sys.exit(7)")[0]
optimized=child("-O","-c","assert False; print('after')")[:2]
with warnings.catch_warnings(record=True) as skipped:
warnings.simplefilter("ignore",UserWarning)
warnings.warn("discard")
ignored=len(skipped)
with warnings.catch_warnings():
warnings.simplefilter("error",UserWarning)
warned=caught(lambda:warnings.warn("promoted"))
report("exceptions",{
"BaseException":[issubclass(c,BaseException) for c in (Exception,SystemExit,KeyboardInterrupt,GeneratorExit)],
"SystemExit":[exit_code,caught(lambda:sys.exit(7))],
"KeyboardInterrupt":caught(lambda:inject(KeyboardInterrupt())),
"Exception":[issubclass(c,Exception) for c in (ValueError,KeyboardInterrupt,SystemExit,GeneratorExit)],
"StopIteration":caught(lambda:next(iter([]))),
"GeneratorExit":[first_yield,actions],
"StandardError":hasattr(builtins,"StandardError"),
"ArithmeticError":[issubclass(c,ArithmeticError) for c in (ZeroDivisionError,OverflowError,FloatingPointError)],
"FloatingPointError":caught(lambda:inject(FloatingPointError("test"))),
"OverflowError":caught(lambda:math.exp(10000)),
"ZeroDivisionError":[caught(lambda:9/0),caught(lambda:9%0)],
"AssertionError":[caught(assert_failed),optimized],
"AttributeError":caught(lambda:getattr(object(),"not_present")),
"EOFError":eof,
"EnvironmentError":EnvironmentError is OSError,
"IOError":[IOError is OSError,missing_result],
"OSError":[issubclass(FileNotFoundError,OSError),missing_result],
"WindowsError":getattr(builtins,"WindowsError",None) is OSError,
"ImportError":caught(lambda:exec("from math import missing_member")),
"LookupError":[issubclass(c,LookupError) for c in (IndexError,KeyError)],
"IndexError":caught(lambda:[][0]),
"KeyError":caught(lambda:{}["missing"]),
"MemoryError":caught(lambda:inject(MemoryError("test"))),
"NameError":caught(lambda:unknown_name),
"UnboundLocalError":caught(unbound),
"ReferenceError":caught(lambda:proxy.count),
"RuntimeError":caught(lambda:next(bad_generator())),
"NotImplementedError":caught(not_implemented),
"SyntaxError":caught(lambda:compile("def (:", "<owned>", "exec")),
"IndentationError":caught(lambda:compile("if True:\nprint(1)", "<owned>", "exec")),
"TabError":caught(lambda:compile("if True:\n\tprint(1)\n print(2)", "<owned>", "exec")),
"SystemError":caught(lambda:inject(SystemError("test"))),
"TypeError":caught(lambda:"x"+4),
"ValueError":caught(lambda:int("north")),
"UnicodeError":[issubclass(c,UnicodeError) for c in (UnicodeEncodeError,UnicodeDecodeError,UnicodeTranslateError)],
"UnicodeDecodeError":caught(lambda:b"\xff".decode("utf8")),
"UnicodeEncodeError":caught(lambda:"北".encode("ascii")),
"UnicodeTranslateError":caught(lambda:inject(UnicodeTranslateError("北",0,1,"test"))),
"Warning":[issubclass(UserWarning,Warning),ignored,warned],
"DeprecationWarning":warning(DeprecationWarning),
"FutureWarning":warning(FutureWarning),
"OverflowWarning":hasattr(builtins,"OverflowWarning"),
"PendingDeprecationWarning":warning(PendingDeprecationWarning),
"RuntimeWarning":warning(RuntimeWarning),
"SyntaxWarning":syntax_warning(),
"UserWarning":warning(None),
})
- 观察清理时序、实际文件权限错误、异常字段、过滤器及真实退出码。
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本章附件与实例包
常见错误与边界检查
- 核对目标解释器版本、环境条件和输入后,再比较实际输出。
技术规范与官方资料
练习与参考解答
查看参考解答
它会覆盖原返回值或屏蔽正在传播的异常。让 finally 只清理资源,再在恰当位置决定结果。