python異常處理try except過程解析

這篇文章主要介紹了python異常處理try except過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

某些時候我們能夠預判程序可能會出現何種類型的錯誤,而此時我們希望程序繼續執行而不是退出,此時就需要用到異常處理;下面是常用的幾種異常處理方法

#通過實例屬性 列表 字典構造對應的異常
class Human(object):
  def __init__(self, name, age, sex):
    self.name = name
    self.age = age
  def get_info(self):
    print("my name is %s,age is %s"%(self.name, self.age))
man1 = Human("李四", 22, "man")
list1 = [1, 2, 3]
dict1 = {"name":"張三", "age":12}
 
#異常捕獲的語法
try:
  man1.get_info1()
except AttributeError as e: #AttributeError爲錯誤類型,此種錯誤的類型賦值給變量e;當try與except之間的語句觸發
# AttributeError錯誤時程序不會異常退出而是執行except AttributeError下面的內容
  print("this is a AttributeError:",e)
finally:
  print("this is finally")
 
try:
  man1.get_info()
  #list1[3]
  #dict1["sex"]
except AttributeError as e:
  print("this is a AttributeError:",e)
else:
  print("一切正常") #當try與except之間內容沒有觸發捕獲異常也沒有異常退出就會跳過except轉到執行else下面的語句
finally:
  print("this is finally")#不論程序是否觸發異常,只要沒有退出都會執行finally下面的內容
 
try:
  list1[3]
  dict1["sex"]
except (IndexError, KeyError) as e: #當需要捕獲多個異常在一條except時候可以使用這種語法,try與except之間語句觸發任意一個異常捕獲後就跳到except下面的語句繼續執行
  print("this is a IndexError or KeyError:",e)
 
try:
  list1[3]
  dict1["sex"]
except IndexError as e:#當需要分開捕獲多個異常可以使用多條except語句,try與except之間語句觸發任意一個異常捕獲後就跳到對應except執行其下面的語句,其餘except不在繼續執行
  print("this is a IndexError:",e)
except KeyError as e:
  print("this is a KeyError:",e)
 
try:
  man1.get_info1()
except IndexError as e:
  print("this is a IndexError:",e)
except Exception as e:
  print("this is a OtherError:",e)#可以使用except Exception來捕獲絕大部分異常而不必將錯誤類型顯式全部寫出來
 
#自己定義異常
class Test_Exception(Exception):
  def __init__(self, message):
    self.message = message
try:
  man1.get_info()
  raise Test_Exception("自定義錯誤")#自己定義的錯誤需要在try與except之間手工觸發,錯誤內容爲實例化傳入的參數
except Test_Exception as e:
  print(e)

推薦我們的python學習基地,點擊進入,看老程序是如何學習的!從基礎的python腳本、爬蟲、django

、數據挖掘等編程技術,工作經驗,還有前輩精心爲學習python的小夥伴整理零基礎到項目實戰的資料

,!每天都有程序員定時講解Python技術,分享一些學習的方法和需要留意的小細節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章