python2.7 學習筆記 (四)——異常

聲明:以下代碼都是在Python2.7+Winxp中執行通過

[異常]
1.try語句的兩種形式
形式1:
try:
<statement>
except<exceptname1>:#出現exceptname1的異常,執行以下語句
<statement>
except<exceptname2>:#出現exceptname2的異常,執行以下語句
<statement>
else:                  #一切正常,執行else語句
<statement>


形式2:
try:
<statement>
except:    #不指定具體異常名,則捕獲所有的異常
<statement>
finally:    #不論異常發生與否,都會執行Finally
<statement>


#-*-coding:utf-8-*-
list = [1,2]
try:
list[3]
except IndexError:  #捕獲數組越界的錯誤
print "Out of index!"
else: 
print "No Error!"


#-*-coding:utf-8-*-

list = [1,2]
try:
list[3] #下標越界error
except : #只要有error ,就會被執行
print "Error eccoured!"


else: 
print "No error !"#沒有error的時候會被執行

finally :
print "Finally will be invoked everytime" #不論有沒有error,都會被執行


2.常用異常名
AttributeError 調用不存在的方法引發的異常
EOFError 遇到文件末尾引發的異常
ImportError 導入模塊出錯引發的異常
IndexError 列表越界引發的異常
IOError I/O 操作引發的異常,如打開文件等
KeyError 使用字典中不存在的關鍵字
NameError 使用不存在的變量名
TabError 語句塊縮進不正常
ValueError 搜索List中不存在的值引發的異常
ZeroDivisionError 除數爲零


3.raise引發異常
#-*-coding:utf-8-*-
#主動raise異常
try:
raise myError  #主動調用一個異常
except myError: #自定義異常
print "My own excepiton!"
else: 
print "No Error!"



#-*-coding:utf-8-*-
#自定義Exception,主動raise 異常
class myException(Exception): #繼承Exception類
def __init__(self,errmsg):#初始化,可以接收參數data
self.errmsg=errmsg

def __str__(self): #重載__str__方法
return "error occured ,msg is :"+self.errmsg


try:
raise myException,"error msg"  #主動調用一個異常
except myException,errmsg: #自定義異常
print str(errmsg)  #這個方法會調用__str__方法,輸出error occured ,msg is :error msg 
else: 
print "No Error!"


4.使用pdb模塊進行調試
run(statement[,globalse[,locals]])
statement:要調試的語句塊
globals:可選參數,設置statement運行的全局環境變量
locals:可選參數,設置statement運行的局部環境變量

本人使用eclipse+pydev進行開發調試,這個……還是略了,不喜歡這種調試方式

另外,也可以使用pythonWin 進行開發調試


15:09 2012-3-15



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章