异常处理

class Dog(object):
    def __init__(self,name):
     self.name=name

    def eat(self,food):
        print("%s eat the milk and pick!%s eat %s"%(self.name,self.name,food))

d=Dog("ALEX")
# choise=input(">>:").strip()
# getattr(d,choise)
data={}
name=[1,2]

方法1

try:
    name[3]
    data['name']
except KeyError as e: #得到错误返回值给e
    print("没有这个key",e)
except IndexError as e: #得到错误返回值给e
    print('列表错误')

##方法2

try:
    name[3]
    data['name']
except (KeyError,IndexError ) as e: #得到错误返回值给e
    print("没有这个key",e)

##方法3(不建议用)
try:
    open("eor.txt")
except Exception as e: #基本能匹配所有的错(不建议用)
    print(" 出错了",e)

Exception运用方法4

try:
    #name[3]
    #data['name']
    pass
except (KeyError,IndexError ) as e: #得到错误返回值给e
    print("没有这个key",e)
except Exception as e: #(通常匹配所有错误放在最后,匹配未知错误)
    print("未知错误",e)
else: #一切正常就执行
    print("一切正常!")
finally:#不管有没有错都执行
    print("不管有没有错都执行")

自定义异常

class hyException(Exception):
    def __init__(self,msg):
        self.message=msg
    def __str__(self): #返回对象的值(对象是self.message)
        return  self.message

try:
    raise hyException("我的异常") #raise主动触发异常
except hyException as e:
    print(e)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章