Python 中使用 assert 语句声明断言,其语法为:
assert 表达式 [, "断言异常提示信息"]
Python 首先检测表达式结果是否为 True,若为 True 则继续向下执行,否则将触发断言异常,并显示断言异常提示信息,后续代码捕获该异常并做进一步处理。例如:
def testAssert(x):
assert x < 1,'无效值'
print ("有效值")
testAssert(1)
上述代码的运行结果如下所示:
>>> def testAssert(x):
… assert x < 1,'无效值'
… print ("有效值")
>>> testAssert(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
testAssert(1)
File "<stdin>", line 2, in testAssert
assert x < 1,'无效值'
AssertionError: 无效值
可见,当 assert 语句判断的表达式结果为 False 时触发了断言异常,此时可以使用 try…except 语句捕获并做进一步处理,例如:
def testAssert(x):
assert x < 1, '无效值'
print("有效值")
try:
testAssert(1)
except Exception:
print("捕获成功")
上述代码的运行结果如下所示:
>>> def testAssert(x):
… assert x < 1, '无效值'
… print("有效值")
>>> try:
… testAssert(1)
… except Exception:
… print("捕获成功")
捕获成功
Python解释器内置的预定义标准异常如表 1 所示。
| 异常名称 | 描述 |
|---|---|
| ArithmeticError | 所有数值计算错误的基类 |
| AssertionError | 断言语句失败 |
| AttributeError | 对象无此属性 |
| BaseException | 所有异常的基类 |
| DeprecationWarning | 关于被弃用的特征的警告 |
| EnvironmentError | 操作系统相关的错误的基类 |
| EOFError | 到达文件尾(EOF, End-of-File)错误 |
| Exception | 常规错误的基类 |
| FloatingPointError | 浮点计算错误 |
| FutureWarning | 关于将来语义会有改变的警告 |
| GeneratorExit | 生成器发生异常通知退出 |
| ImportError | 引入模块/对象失败 |
| IndentationError | 缩进错误 |
| IndexError | 序列中无此索引 |
| IOError | 输入/输出操作失败 |
| Keyboardlnterrupt | 用户中断执行 |
| KeyError | 映射中无此键 |
| LookupError | 无效数据查询的基类 |
| MemoryError | 内存溢出错误 |
| NameError | 未声明/初始化对象,名称调用错误 |
| NotImplementedError | 尚未实现的方法 |
| OSError | 操作系统错误 |
| OverflowError | 数值运算超出最大限制 |
| PendingDeprecationWarning | 关于特性将会被废弃的警告 |
| ReferenceError | 弱引用试图访问已经被回收的对象 |
| RuntimeError | 一般运行时错误 |
| RuntimeWarning | 运行时行为警告 |
| StandardError | 所有内建标准异常的基类 |
| StopIteration | 迭代器没有更多的值 |
| SyntaxError | Python语法错误 |
| SyntaxWarning | 语法警告 |
| SystemError | 一般的解释器系统错误 |
| SystemExit | 解释器请求退出 |
| TabError | Tab和空格混用 |
| TypeError | 对类型无效的操作 |
| UnboundLocalError | 访问未初始化的本地变量 |
| UnicodeDecodeError | Unicode解码错误 |
| UnicodeEncodeError | Unicode编码错误 |
| UnicodeError | Unicode相关错误 |
| UnicodeTranslateError | Unicode转换错误 |
| UserWarning | 用户代码生成的警告 |
| ValueError | 传入无效参数 |
| Warning | 各种警告的基类 |
| WindowsError | 系统调用失败 |
| ZeroDivisionError | 除(或取模)零错误 |
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/21399.html