Python之異常處理-Exception,python-exception
在寫python程式時, 不要害怕報錯, 也不要怕自己的英語不夠好, 不要看到一有紅色的字就心裡發慫. 其實報的錯也是有套路可尋滴~識別了異常的種類, 才能對症下藥.
常見異常:
Exception 所有異常的基類
AttributeError 特性應用或賦值失敗時引發
IOError 試圖開啟不存在的檔案時引發
IndexError 在使用序列中不存在的索引時引發
KeyError 在使用映射不存在的鍵時引發
NameError 在找不到名字(變數)時引發
SyntaxError 在代碼為錯誤形式時引發
TypeError 在內建操作或者函數應用於錯誤類型的對象是引發
ValueError 在內建操作或者函數應用於正確類型的對象,但是該對象使用不合適的值時引發
ZeroDivisionError 在除法或者摸除操作的第二個參數為0時引發
1. 拋出異常
def div(x,y): if y == 0: raise ZeroDivisionError('Zero is not allowed.') return x/ytry: div(4,0)except Exception as e: print(e)
Zero is not allowed.Process finished with exit code 0
2. 捕捉異常:
可同時捕捉多個異常,可捕捉異常對象,可忽略異常類型以捕捉所有異常
try: x = int(input('input x:')) y = int(input('input y:')) print('x/y = ',x/y) except ZeroDivisionError: #捕捉除0異常 print("ZeroDivision") except (TypeError,ValueError) as e: #捕捉多個異常,並將異常對象輸出 print(e) except: #捕捉其餘類型異常 print("it's still wrong")
input x:3input y:0ZeroDivisionProcess finished with exit code 0
input x:5input y:ainvalid literal for int() with base 10: 'a'Process finished with exit code 0
try/except 可以加上 else 語句,實現在沒有異常時執行什麼
try: x = int(input('input x:')) y = int(input('input y:')) print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0異常 print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多個異常,並將異常對象輸出 print(e)except: #捕捉其餘類型異常 print("it's still wrong")else: #沒有異常時執行 print('it works well')
input x:4input y:2x/y = 2.0it works wellProcess finished with exit code 0
3. finally 語句
不管是否出現異常,最後都會執行finally的語句塊內容,用於清理工作
所以,你可以在 finally 語句中關閉檔案,這樣就確保了檔案能正常關閉
try: x = int(input('input x:')) y = int(input('input y:')) print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0異常 print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多個異常,並將異常對象輸出 print(e)except: #捕捉其餘類型異常 print("it's still wrong")else: #沒有異常時執行 print('it works well')finally: #不管是否有異常都會執行 print("Cleaning up")
input x:4input y:ainvalid literal for int() with base 10: 'a'Cleaning upProcess finished with exit code 0
異常拋出之後,如果沒有被接收,那麼程式會拋給它的上一層,比如函數調用的地方,要是還是沒有接收,那繼續拋出,如果程式最後都沒有處理這個異常,那它就丟給作業系統了 -- 你的程式崩潰了