Python daily--sample of Exception

来源:互联网 发布:重庆大数据招聘 编辑:程序博客网 时间:2024/06/06 00:54

一个异常处理的例子:

#!/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
>>> 

0 0
原创粉丝点击