文章目录
- 用 raise 手工抛出异常
- 代码示例
- assert 语句
- 代码示例
- 自定义异常类
在上一篇文章的程序里,所有的异常都是在程序运行中出现了错误而引发的异常,程序员还可以在 python 中使用 raise语句来
引发指定的异常,并向异常传递数据。
根据程序的需要,程序员还可以自定义新的异常类型,例如对用户输入文本的长度有要求,则可以使用 raise 引发异常,以确保文本输入长度符合要求
用 raise 手工抛出异常
使用 raise 有以下几种使用方式:
raise <异常名>
raise <异常名, 附加数据>
raise <类名>
使用 raise 可以抛出各种预定的异常,即使程序在运行时根本不会引发该异常
代码示例
# -*- coding:utf-8 -*-
def testRaise1():
for i in range(5):
if i == 2:
raise NameError
print(i)
print('end...')
def testRaise2():
for i in range(5):
try:
if i==2:
raise NameError
except NameError:
print('raise a NameError!')
print(i)
print('end...')
testRaise2()
testRaise1()
运行结果(先调用处理异常的testRaise2):
stark@appledeMacBook-Air Desktop % python Raise.py
0
1
raise a NameError!
2
3
4
end...
0
1
Traceback (most recent call last):
File "Raise.py", line 20, in <module>
testRaise1()
File "Raise.py", line 5, in testRaise1
raise NameError
NameError
assert 语句
一般形式如下:
assert <条件测试>,<异常附加数据>
其中异常附加数据是可选的
assert 语句是简化的 raise 语句,它引发异常的前提是其后面的条件测试为假
代码示例
# -*- code:utf-8 -*-
def testAssert():
for i in range(3):
try:
assert i<2
except AssertionError:
print('raise a AssertionError!')
print(i)
print('end...')
testAssert()
测试结果
stark@appledeMacBook-Air ~ % python -u "/Users/stark/Desktop/assert.py"
0
1
raise a AssertionError!
2
end...
assert 语句一般用于程序开发时测试代码的有效性。比如某个变量的值必须在一定范围内,而运行时得到的值不符合要求,则引发该异常,对开发者予以提示。所以一般在程序开发中不去捕获这个异常,而是让它中断程序。
assert 语句不是总运行的,只有 python 中的一个内置的特殊变量__debug__
为 True 时才运行。要关闭程序的 assert 语句就使用 python-O
(短线,后接大写字母O)来运行程序(terminal 或 command)
自定义异常类
自定义异常类不用从基础完全自己定义,只要通过继承 Exception 类来创建即可。最简单的自定义异常类类体可以是 pass ···
==如果需要异常类带有一定的提示信息,也可以重载__init__
和__str__
这两个方法