处理异常
try:
text = input('Enter somint -->')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You Cancelled the operation,')
else:
print('You entered {}'.format(text))
抛出异常
# encoding=UTF-8
class ShortInputException(Exception):
def __init__(self,length,atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter somethin -->')
if len(text) < 3:
raise ShortInputException(len(text),3)
except EOFError:
print('Why did you do an EOF on me')
except ShortInputException as ex:
print('ShortInputException: the input was'+
'{0} long ,expected at least {1}'
.format(ex.length,ex.atleast))
else:
print('No exception was raised')
Try ... Finally 使用
#encoding=UTF-8
import sys
import time
f = None
try:
f = open('poem.txt')
while True:
line = f.readline()
if len(line) == 0:
break
print(line,end=' ')
sys.stdout.flush()
print('Press ctrl+c now')
time.sleep(2)
except IOError:
print('Cound not find file poem.txt')
except KeyboardInterrupt:
print('!!! You cancelled the reading from the file.')
finally:
if f:
f.close()
print('Cleaning up:closed the file')
with 语句
with open('poem.txt') as f:
for line in f:
print(line,end='')