python 異常處理 try except


什么是異常  

異常就是程序運行時發生錯誤的信號,程序隨即發生終止行為 

 

常見的異常有哪些 

AttributeError 試圖訪問一個對象沒有的樹形,比如foo.x,但是foo沒有屬性x
IOError 輸入/輸出異常;基本上是無法打開文件
ImportError  無法引入模塊或包;基本上是路徑問題或名稱錯誤
IndentationError  語法錯誤(的子類) ;代碼沒有正確對齊
IndexError  下 標索引超出序列邊界,比如當x只有三個元素,卻試圖訪問x[5]
KeyError  試圖訪問字典里不存在的鍵
KeyboardInterrupt  Ctrl+C被按下
NameError  使用一個還未被賦予對象的變量
SyntaxError Python代碼非法,代碼不能編譯(個人認為這是語法錯誤,寫錯了)
TypeError 傳入對象類型與要求的不符合
UnboundLocalError 試圖訪問一個還未被設置的局部變量,基本上是由於另有一個同名的全局變量,
導致你以為正在訪問它
ValueError 傳入一個調用者不期望的值,即使值的類型是正確的

異常的類型 

常見的有語法錯誤 (語法錯誤需要在 python 執行前改正)

 

邏輯錯誤 

 

常見的異常的處理 方式

# 語法結構一

try:

  被檢測的代碼塊

except 異常類型:

try 中一旦檢測到異常,就執行這個位置的邏輯

示列

try:
    f1 = open('test.txt')
    g = (line.strip() for line in f1)
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopAsyncIteration:
    f1.close()

讀取test.txt 文件中的文件,當檢測到異常,就拋出  StopAsyncIteration,然后關閉文件 

 

# 語法結構二 

# 多分支

s1 = 'hello python'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)

#語法結構三  萬能的異常

s1 = 'hello Python'
try:
    int(s1)
except Exception as e:
    print(e)

# 語法結構三 多分支異常 新增  Exception

s1 = 'hello python'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
except Exception as e:
    print(e)

# 語法結四 當try 的時候沒有異常時執行 else  ,無論是否異常都執行 finally

s1 = 100
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
else:
    print('try內代碼塊沒有異常則執行我')
finally:
    print('無論異常與否,都會執行該模塊,通常是進行清理工作')

 

主動觸發異常 

try:
    raise TypeError('類型錯誤')
except Exception as e:
    print(e)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM