try..except
通常的语句放在try-块中,
而把错误处理语句放在except-块中。
import sys
try:
s=raw_input('Enter something---->')
except EOFError:
print '\n why did you do an eof on me'
sys.exit()
except:
print '\n some error/exception occurred.'
print 'done'
引发异常
使用raise语句 引发 异常.
指明错误/异常的名称和伴随异常 触发的 异常对象
引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类。
class ShortInputException(Exception):
'''a user-defined exception class'''
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)
#other work can continue as usual here
except EOFError:
print 'why did you do an eof on me'
except ShortInputException,x:
print 'ShortInputException:the input was of length %d,\
was excepting at least %d '%(x.length,x.atleast)
else:
print 'no error!'
try..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....'