一个异常处理的例子:
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
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'
例子2
#!/usr/bin/python
# Filename: finally.py
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 KeyboardInterrupt:
print ('\nWhy did u do an EOF on me?')
finally:
f.close()
print('Cleaning up...closed the file')
执行结果:<当打印的时候点击ctrl+c>
>>> ================================ RESTART ================================
>>>
sean
Why did u do an EOF on me?
Cleaning up...closed the file
>>>