当程序中出现某些异常的状况时,异常就发生了。python中可以使用try ... except 处理。
try:
print 1/0
except ZeroDivisionError, e:
print e
except:
print "error or exception occurred."
#integer division or modulo by zero
可以让try ... except 关联上一个else,当没有异常时则执行else。
我们可以定义自己的异常类,需要继承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 someting-->")
if len(s) < 3:
raise ShortInputException(len(s), 3)
except EOFError:
print "why you input an EOF?"
except ShortInputException, ex:
print "The lenght of input is %d, was expecting at the least %d" % (ex.length, ex.atleast)
else:
print "no exception"
#The lenght of input is 1, was expecting at the least 3
try...finally
try:
f = file("test.txt")
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print "Cleaning up..."
已有 22658 名学员学习以下课程通过考试
最需教育客户端 软件问题一手掌握
去 App Store 免费下载 iOS 客户端
点击加载更多评论>>