本章主要内容
- 用try语句捕获异常
- 常见异常处理
- 用raise 和assert抛出异常
- 自定义异常
常用异常名
异常名 | 描述 |
---|---|
AttributeError | 调用不存在方法异常 |
EOFError | 遇到文件末尾异常 |
ImportError | 导入模块或包出错 |
IndexError | 列表越界引发异常 |
IOError | I/o操作引发异常如文件打开失败等 |
KeyError | 使用字典中不存在的关键字异常 |
NameError | 使用不存在的变量名异常 |
TabError | 语句块缩进不正确 |
ValueError | 搜索列表不存在的值引发异常 |
ZeroDivisionError | 除数为零引发异常 |
def testTry(index,flag=False):
stulst = ('johan','jenny','tom')
if flag:
try:
astu = stulst[index]
except IndexError: #捕获越界异常
print('IndexError')
return 'Try Test Finished!'
else:
astu = stulst[index]
return 'no try test finished!'
print('Right params testing start')
print(testTry(1,True)) #捕获异常True
print(testTry(1,False)) #不捕获异常
print('Error params testing start')
print(testTry(4,True)) #越界参数,捕获异常
print(testTry(4,False)) #越界参数,不捕获异常
Right params testing start
Try Test Finished!
no try test finished!
Error params testing start
IndexError
Try Test Finished!
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-1-a18c21a5bb46> in <module>()
15 print('Error params testing start')
16 print(testTry(4,True)) #越界参数,捕获异常
---> 17 print(testTry(4,False)) #越界参数,不捕获异常
<ipython-input-1-a18c21a5bb46> in testTry(index, flag)
8 return 'Try Test Finished!'
9 else:
---> 10 astu = stulst[index]
11 return 'no try test finished!'
12 print('Right params testing start')
IndexError: tuple index out of range
def testTryFinally(index):
stulst = ['johan','jack','Tom']
af = open('my.txt','wt+')
try:
af.write(stulst[index])
except: #捕获所有异常
pass
finally: #无论是否越界异常都关闭文件
af.close()
print('file already had been closed!')
print('NO IndexError...')
testTryFinally(1) #无越界异常
print('IndexError...')
testTryFinally(4) #有越界异常
NO IndexError...
file already had been closed!
IndexError...
file already had been closed!
def testTryOne(index,i):
stulst = ['johan','jenny','Tom']
try:
print(len(stulst[index])/i)
except IndexError: #只捕获越界异常
print('Error!')
print('Try one...Right')
testTryOne(1,2) #正常
print('Try one...Error')
testTryOne(4,2) #捕获越界异常
print('NO try Error')
testTryOne(1,0) #除0异常未被捕获
Try one...Right
2.5
Try one...Error
Error!
NO try Error
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-3-c8e1e18cc7a2> in <module>()
10 testTryOne(4,2) #捕获越界异常
11 print('NO try Error')
---> 12 testTryOne(1,0) #除0异常未被捕获
<ipython-input-3-c8e1e18cc7a2> in testTryOne(index, i)
2 stulst = ['johan','jenny','Tom']
3 try:
----> 4 print(len(stulst[index])/i)
5 except IndexError: #只捕获越界异常
6 print('Error!')
ZeroDivisionError: division by zero
'''
手动抛出异常可以用在特定
时候中断程序
'''
def testRaise():
for i in range(5):
try:
if i==2:
raise NameError #当i==2时手动抛出异常
except NameError: #捕获变量异常不中断程序
print('Raise a NameError!')
print(i)
print('end...')
testRaise()
0
1
Raise a NameError!
2
3
4
end...
'''
assert异常:
当条件为假时候抛出异常
'''
def testAssert():
for i in range(3):
try:
assert i<2
except AssertionError:
print('Raise a AssertionError')
print(i)
print('end....')
testAssert()
0
1
Raise a AssertionError
2
end....
'''
自定义异常类:
不用完整的定义异常类
可以通过继承Exception类
来定义
'''
class MyError(Exception): #定义异常类
pass
raise MyError('MyError') #抛出异常中断程序
print('end......') #此语句未执行
---------------------------------------------------------------------------
MyError Traceback (most recent call last)
<ipython-input-6-02e5a3a3549c> in <module>()
7 class MyError(Exception): #定义异常类
8 pass
----> 9 raise MyError('MyError') #抛出异常中断程序
10 print('end......') #此语句未执行
MyError: MyError
总结:
为了保证程序正常运行部中断才催生出了异常处理,异常处理还可以用来控制程序执行到什么地方,什么地方中断程序。
今天先到这里,。。。。玩会台球去。。。。。
网友评论