就像C,C++中的异常捕捉一样,不过不同于try,,catch这种,而是try...except...语句来接收这个异常。
1.打开一个不存在的文件时会抛 IOError 异常,用下列例子捕捉这个异常
try:
open("a.txt",'r')
except IOError:
print "buzhuoyicang"
2.name异常
try:
print aa
except NameError:
print "name eroor"
3.异常有很多种类,一一记住有些困难,在 Python 中所有的异常类都继承 Exception,所以我们可以使用它来接收所有的异常。
try:
print aa
except Exception: #用Exception处理所有异常
print "name eroor"
除了这些基本的异常处理方法,看看其他更多的异常处理方法
1.try.....except......else...这种操作,异常发生,捕获异常,异常不发生,执行else中语句
try:
aa = '异常测试'
print aa
except Exception,msg:
print msg
else:
print '无异常'
2.try....finally......有些情况下不管是否出现异常这些操作都能被执行
前提条件,建立一个test.txt文件,填上内容
import time
files = file("test.txt",'r')
strs = files.readlines()
try:
for i in strs:
print i
time.sleep(2) #每隔2s打印一行
finally:
files.close()
print 'cleaning up..close the file'