異常類型的檢測、處理和抛出:
異常的檢測可以使用try語句來實作,任何出現在try語句範圍内的異常都會被檢測到。下面将介紹兩種形式的try語句:一種是try-except,另一種是try-finally。
①try-except語句:
try:
檢測範圍
except Exception[as reason]: # as reason可以報出異常具體的内容是什麼,然後列印出來
出現異常(Exception)後的處理代碼
try:
f = open("我是一個檔案.txt")
print(f.read())
f.close()
except OSError as reason:
print("檔案打開出錯")
print("錯誤原因是:" + str(reason)) # 注意reason的強制轉換
檔案打開出錯
錯誤原因是:[Errno 2] No such file or directory: '我是一個檔案.txt'
一個try語句還可以和多個except語句進行搭配
多個except語句也可以整合成一個except語句,如:except (OSError, TypeError):
②try-finally語句,finally語句塊的内容一定會被執行。通常會和except一起用:
try:
檢測範圍
except Exception [as reason]:
出現異常(Exception)後的處理代碼
finally:
無論如何都會被執行的代碼
try:
f = open("我是一個檔案.txt", 'w')
print(f.write("我是一個檔案"))
sum = 1 +'1'
#f.close() 如果不使用finally語句,關閉檔案操作在這執行的話,則内容由于異常中斷,仍然存在在Python的緩沖區中,并未寫入檔案中
except (OSError, TypeError) as reason:
print("檔案打開出錯")
print("錯誤原因是:" + str(reason))
finally:
f.close()
由raise語句自己引發一個異常:
>>> raise #直接raise一下就産生一個異常,但一般加上一個異常的名字
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
raise #直接raise一下就産生一個異常,但一般加上一個異常的名字
RuntimeError: No active exception to reraise
>>> raise ZeroDivisionError
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError("除數為0的異常") #可以給異常加上一個參數
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
raise ZeroDivisionError("除數為0的異常") #可以給異常加上一個參數
ZeroDivisionError: 除數為0的異常
一些常見的異常:http://bbs.fishc.com/thread-45814-1-1.html
這篇文章感覺很詳細:http://www.jb51.net/article/41972.htm