python中常見的異常

2022-07-10 01:48:10 字數 963 閱讀 6376

python常見的異常:

baseexception:新的異常類的基類

exception:所有異常類的基類,但繼承自baseexception

assertionerror:assert語句是吧

filenotfounderror:試圖開啟乙個不存在的檔案或目錄

attributeerror:試圖訪問的物件沒有屬性

nameerror:使用乙個還未賦值物件的變數

indexerror:當乙個序列超出範圍時,引發此異常

syntaxerror:當解析器遇到乙個語法錯誤時引發此異常

keyboardinterrupt:組合鍵crtl+c被按下,程式強行終止

typeerror:傳入的物件型別與要求不符

用法try:

open "abc.txt",'r'

print(a)

except baseexception:

print(「異常了!」)

ps:列印出異常資訊的

try:

a = 「異常測試」

print(a)

except nameerror as msg

print(msg)

else:

print("沒有異常時執行」)

ps:沒有異常執行else的指令

try:

print(a)

except nameerror as msg:

print(msg)

finally:

print("不管是否出現異常,都會被執行「)

#定義say_hellow()函式

def say_hellow(name=none):

if nam is none:

raise nameerror('"name" cannot be empty')

else:

print("hellow,%s", %name)

python中常見的異常

python常見異常型別大概分為以下類 1.assertionerror 當assert斷言條件為假的時候丟擲的異常 2.attributeerror 當訪問的物件屬性不存在的時候丟擲的異常 3.indexerror 超出物件索引的範圍時丟擲的異常 4.keyerror 在字典中查詢乙個不存在的ke...

python中常見的異常

python中的異常 zerodivision 除數為0 indexerror 索引值超出範圍 取列表或字串中元素可能出現 keyerror 關鍵字在字典中不存在 nameerror 訪問的變數不存在 assertionerror 斷言不成立 asser語句不成立 try 檢測範圍語句塊 excep...

Python中常見的異常總結

python中常見的異常總結 當python 檢測到乙個錯誤時,直譯器就會指出當前流已經無法繼續執行下去,這時候就出現了異常。一 異常錯誤 a 語法錯誤 錯誤一 if錯誤二 def text pass 錯誤三 print sjds b 邏輯錯誤 使用者輸入不完整 比如輸入為空 或者輸入非法 輸入不是...