异常
程序出现某些异常的状况时候,异常就发生了。最常见的是如果要读取文件时候,文件不存在,或者运行时不小心删除了,再访问就会出现异常。
错误:如果有错误,源码是无法执行的,并且会打印出错误的地方。
try ... except
>>> S = raw_input('Enter something-->');
Enter something-->
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
S = raw_input('Enter something-->');
EOFError: EOF when reading a line
EOFError Python引发了一个成为EOFError的错误,这个错误基本上是意味着它发现了一个不期望的文件尾。
(这个文件尾是由Ctrl-d引起的)
异常处理:
使用try ... except语句来处理异常。通常将语句放在try-块中,而把我们的错误处理语句放在except-块
例子:
#!/usr/bin/python
#Filename : try_except.py
import sys;
try:
s = raw_input('Enter something -->');
except EOFError: # catch EOFError
print '\nWhy did you do an EOF on me?';
sys.exit(); # exit the program
except: # Catch any error
print '\n Some error/exception occurrd.';
# here, we are not exiting the program
print 'Done';
except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或
异常的名称,它会处理所有的错误和异常。对于每一个try从句,至少有一个相关联的except从句。
如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序,并且打印一个消息。
也可以使用try...catch块关联一个else从句。当没有异常的时候,else从句将被执行。
引发异常:
使用raise语句引发异常,还需要指明错误/异常的名称或伴随异常触发的异常对象。引发的错误或异常
应该分别从一个Error或Exception类直接或间接导出类。
#!/usr/bin/python
#Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self);
self.length = length;
self.atleast = atleast;
try:
s = raw_input('Enter something-->');
if len(s) < 3:
raise ShortInputException(len(s), 3);
#Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?';
except ShortInputException, x:
print 'ShortinputExcetion: The input was of length %d, was excepting at least %d' %(x.length, x.atleast);
else:
print 'No exception was raised.';
此处创建了一个自己的异常类型,可以使用预定义的异常/错误。新的异常类型ShortInputException,两个域
length是给定的输入的长度,atleast则是程序期望的最小的长度。
使用finally
#!/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 'Clean up... closed the file';
使用time.sleep(2)故意让程序休眠2秒,这样可以有时间按下ctrl-c。
按下ctrl+c后,程序中断,出发KeyboardInterrupt异常被触发,程序退出,但是退出之前,finally从句依然要被执行。