JS 進階需要掌握的13個概念
更多python教程請到: 菜鳥教程www.piaodoo.com
人人影視www.sfkyty.com
這篇文章主要介紹了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)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援菜鳥教程www.piaodoo.com。