異常
程序出現某些異常的狀況時候,異常就發生了。最常見的是如果要讀取文件時候,文件不存在,或者運行時不小心刪除了,再訪問就會出現異常。
錯誤:如果有錯誤,源碼是無法執行的,並且會打印出錯誤的地方。
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從句依然要被執行。