#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:#处理EOFError类型的异常
print '/nWhy did you do an EOF on me?'
sys.exit() # 退出程序
except:#处理其它的异常
print '/nSome error/exception occurred.'
print 'Done'
运行输出如下:$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional!
Done
说明:每个try语句都必须有至少一个except语句。如果有一个异常程序没有处理,那么Python将调用默认的处理器处理,并终止程序且给出提示。
#!/usr/bin/python
# Filename: finally.py
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...closed the file'
运行输出如下:$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
File "finally.py", line 12, in ?
time.sleep(2)
KeyboardInterrupt