python中常見的異常如表所示。
1、通常else 語句只有在沒有異常的情況下才會被執行
try:2、有些情況下不管是否出現異常,這些操作都希望能被執行,例如檔案的關閉、鎖的釋放、把資料庫連線返還給連線池等操作。我們可以使用try…except…finally…語句來實現這樣。aa = "異常測試:"
print(aa)
except baseexception as msg:
print(msg)
else:
print("沒有異常!")
try:3、丟擲異常print(bb)
except baseexception as e:
print(e)
finally:
print("不管有沒有異常,我都會被執行!")
print()方法只能列印錯誤資訊,python中提供了 raise方法來丟擲乙個異常資訊。
from random import randintnumber=randint(1,9)
if number%2 == 0:
raise nameerror("%d is even"%number)
else:
raise nameerror("%d is odd"%number)
常見的Python異常
異常 描述assertionerror assert 斷言 語句失敗 attributeerror 試圖訪問乙個物件沒有的屬性,比如foo.x,但是foo沒有屬性x ioerror 輸入 輸出異常 基本上是無法開啟檔案 importerror 無法引入模組或者包 基本上是路徑問題 indentati...
常見的python異常
assertionerror assert 斷言 語句失敗 attributeerror 試圖訪問乙個物件沒有的屬性 ioerror 輸入輸出異常,基本是無法開啟檔案 importerror 無法匯入模組或包,基本是路徑問題 indentationerror 無法錯誤,沒有正確的對齊 indexer...
python常見異常
目錄 1.2 異常 python 中的錯誤有兩種,語法錯誤和邏輯錯誤 這種錯誤是我們應該避免的 python中的異常是程式執行過程中產生的,有異常不一定要把程式停止,只要把異常丟擲,然後檢視異常產生的原因即可。1.2.1 python中的異常種類attributeerror 試圖訪問乙個物件沒有的屬...