python 異常
當程序中出現(xiàn)某些異常的狀況時,異常就發(fā)生了。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 關聯(lián)上一個else,當沒有異常時則執(zhí)行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..."
點擊加載更多評論>>