#coding:UTF-8
#try.. except 开始
'''
我们把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。
except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。
如果没有给出错误或异常的名称,它会处理 所有的 错误和异常。
对于每个try从句,至少都有一个相关联的except从句。
如果某个错误或异常没有被处理,默认的Python处理器就会被调用。
它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理。
你还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。
'''
import sys
try:
s=raw_input("Enter something -->")
except EOFError: #ctrl+d 测试
print 'Why did you do an EOF on me?'
sys.exit()
except:
print'some error/exception occurred.'
print 'Done!'
#try.. except 结束
#============================
#引发异常 开始
class ShortInputException(Exception):
def __init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
try:
s=raw_input('Enter something-->')
if len(s)<3:
raise ShortInputException(len(s),3)
except EOFError:
print 'Why did you do an EOF on me?'
except ShortInputException,x:
print 'ShortInputException: The input was of length %d,\
was expecting at least %d ' %(x.length,x.atleast)
else:
print 'No exception was raised.'
'''
结果
输出
Enter something --> # ctrl+d
Why did you do an EOF on me?
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
Enter something --> abc
No exception was raised.
'''
#引发异常 结束
#=====================================
#try..finally 开始
'''
在一个try块下,你可以同时使用except从句和finally块。
如果你要同时使用它们的话,需要把一个嵌入另外一个。
'''
import time
try:
f=file('poem.txt')
while True:
line=f.readline()
if len(line)==0:
break;
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up... closed the file'
'''
结果
Programming is fun
Cleaning up... closed the file
Traceback (most recent call last):
File "E:\python_test\8_异常.py", line 74, in <module>
time.sleep(2)
KeyboardInterrupt
'''
'''
在程序运行的时候,按Ctrl-c中断/取消程序。
我们可以观察到KeyboardInterrupt异常被触发,程序退出。
但是在程序退出之前,finally从句仍然被执行,把文件关闭
'''
#try..finally 结束
python学习笔记——8_异常
最新推荐文章于 2019-07-03 22:50:44 发布