本文作爲自己的學習筆記,已盡力詳細描述和準確,難免會出現錯誤,所以這是一個beta版本。
首先什麼是異常,
在python或者程序中,由於語法,邏輯或者系統的錯誤而導致程序出現錯誤無法執行,而這個錯誤就是異常。
異常分爲兩個階段:
1,引起異常發生的錯誤
2,檢測(也就是採取措施)階段
python中的異常分爲很多種,常見的有如下異常:
1,NameError
>>> foo
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
foo
NameError: name 'foo' is not defined
2,SyntaxError: Python解釋器語法錯誤
>>> for
SyntaxError: invalid syntax
3,KeyError:請求一個不存在的字典關鍵字
4,IOError:輸入/輸出錯誤
等等。所有錯誤的分類如下:
-BaseException
|-KeyboardInterrput
|-SystemExit
|-Exception(除了以上連個異常,所有的異常分類到這裏)
|-(all other current built-in exceptions)
在python中如何捕獲異常
try:
try_suite
except Exception[,reasion]:
except_suite
注意在 except 中的代碼塊,在異常沒有發生時,這些代碼塊是永遠不會到達。
例:
try:
f = open('blah','r')
except IOError, e:
print 'could not open file:',e
同樣的情況下,try後面可以跟多個except 來處理不同的異常,當然也可以跟一個來處理同類的異常,語法分別如下:
try:
try_suite
except Exception [,reason1]:
suite_for_exception_Exception1
except Exception [,reason2]:
suite_for_exception_Exception2
:
處理多個異常的except 語句:
try:
try_suite
except (Exception1,Exception2) [,reason1]:
suite_for_exception_Exception1_and_Exception2
例:
import sys
try:
s = raw_input('Enter something -->')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit()
except:
print '\nSome error/exception occurred.'
print 'Done'
例:
def safe_float(obj):
try:
retval= float(obj)
except (ValueError,TrypeError):
retval ='argument must be a number or numeric string'
return retval
另外一個用戶是捕獲所有的異常,但是我建議這樣子做
try:
:
except Exception,e:
suit_Exception
else 子句:
在try 範圍中沒有異常被檢測到時,執行else子句。
例:
import 2rd_party_module
log = open('logfile.txt','w')
try:
3rd_party_module.function()
except:
log.write("*** caught exception in module\n")
else:
log.write("*** no exception caught\n")
finally 子句
try:finally不是用來捕獲異常,而是來替代的
try:
try_suite
finally:
finallyu_suite #無論如何都要執行
try-except-else-finally:
try:
try_suite
except Exception1:
suite_for_Exception1
except (Exception2,Exception3,Exception4):
suite_for_Exception_2_3_and4
except Exception5,Argument5:
suite_for_Exception_plus_argument
except:
suite_for_all_other_exceptions
else:
no_exceptions_detected_suite
finally:
always_execute_suite
觸發異常
raise
例:
#/usr/bin/env python
try:
assert 1==0,'one does not equal zero siily!'
except AssertionError,arges:
print '%s: %s' %(arges.__class__.__name__,arges)