python的异常处理也是很简单的东西。
和其他语言的异常处理没什么太大的区别。
主要使用try...except 语句来进行的
import sys
try:
s = raw_input('Enter something --> ')
except SystemExit:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
使用ctrl+d来触发这个异常
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 '\nWhy 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.'
下面是使用finlly和try...except嵌套
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
except IOError:
print 'IOError'
finally:
try:
f.close()
except NameError:
print 'NameError'
print 'Cleaning up...closed the file'