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),
})
本例需在 Windows CPython 3.12 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12
入口文件:projects/python-legacy-lab/legacy-exceptions-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
legacy-exceptions-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202611a446.zip