
1.例外處理
例外:在運行代碼程序中遇到的任何錯誤,大有error字樣的都為例外
例外處理:對代碼中所有可能會出現的例外進行處理
疑問:我們為什么要處理例外?
2.例外代碼
import os #創建一個已存在的檔案夾 os.mkdir("Eclipse") #例外:FileExistsError: [WinError 183] 當檔案已存在時,無法創建該檔案,: 'Eclipse'
3.捕獲指定例外
import os try:#捕獲例外 #創建一個已存在的檔案夾 os.mkdir("Eclipse") #例外:FileExistsError: [WinError 183] 當檔案已存在時,無法創建該檔案,: 'Eclipse' except FileExistsError:#處理指定例外 print("已捕獲例外,在這里處理...")
4.捕獲全部例外
第二種:
import os try:#捕獲例外 #創建一個已存在的檔案夾 os.mkdir("Eclipse") #例外:FileExistsError: [WinError 183] 當檔案已存在時,無法創建該檔案,: 'Eclipse' except:#只要有例外就處理 print("已捕獲例外,在這里處理...")
第二種: import os try:#捕獲例外 #創建一個已存在的檔案夾 os.mkdir("Eclipse") #例外:FileExistsError: [WinError 183] 當檔案已存在時,無法創建該檔案,: 'Eclipse' except Exception:#只要有例外就處理 print("已捕獲例外,在這里處理...")
5.捕獲例外并處理
import os try: os.mkdir("Eclipse") except Exception as e: print("捕獲一個例外:{0}".format(e)) file = open("eror.txt","a",encoding="utf8") file.write("\n"+str(e)) file.close()
6.try...except...finally
#finally 不管是否有例外都執行
#try...except...finally import os try: os.rmdir("Arr/Brr")#洗掉一個不存在的路徑 except Exception as e: print("處理例外:{0}".format(e))#處理例外:[WinError 3] 系統找不到指定的路徑,: 'Arr/Brr' finally: print("不管是否報錯都執行") #try...except...else
7.try...except...else
#else 不報例外執行
#try...except...else import os try: os.rmdir("Arr/Brr")#洗掉一個不存在的路徑 except Exception as e: print("處理例外:{0}".format(e))#處理例外:[WinError 3] 系統找不到指定的路徑,: 'Arr/Brr' else: print("不報例外執行")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/540224.html
標籤:Python
