异常处理
try:
text=input('Enter something-->')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
else:
print('You entered {}'.format(text))
结果:输入“asd”
Enter something-->asd
You entered asd
结果:键入“Ctrl+d”
Enter something-->Why did you do an EOF on me?
抛出异常:
class ShortInputException(Exception):
'''一个由用户定义的异常类'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
try:
text=input('Enter something-->')
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.')
结果:
Enter something-->asd
No exception was raised.
Enter something-->a
ShortInputException: The input was 1 long,expected at least 3
无异常的即“else”
另一个例子(注意,ctrl+c要在命令行中才有用)
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("can't find")
except KeyboardInterrupt:
print("cancel reading")
finally:
if f:
f.close()
print("(Cleaning up:Closed the file)")
input()
正如上面这样,一般选择在try中打开资源,而在finally里释放资源
两种读文本的方式:
with open('poem.txt')as f:
for line in f:
print(line,end=' ')
f=open('poem.txt')
while True:
line=f.readline()
if(len(line)==0):
break
print(line,end=' ')
f.close()
可以看到,with语法更为简单